我想我已經開始掌握了這一點。對於此代碼:縮短Python 3.x中的重複代碼?
printedxrow7 = ["V "+str(cols[0].count(0)),"V "+str(cols[1].count(0)),"V "+str(cols[2].count(0)),"V "+str(cols[3].count(0)),"V "+str(cols[4].count(0))]
printedxrow8 = [str(sum(cols[0])),str(sum(cols[1])),str(sum(cols[2])),str(sum(cols[3])),str(sum(cols[4]))]
numgood = (((rows[0]).count(2))+((rows[0]).count(3)+(rows[1]).count(2))+((rows[1]).count(3))+((rows[2]).count(2))+((rows[2]).count(3))+((rows[3]).count(2))+((rows[3]).count(3))+((rows[4]).count(2))+((rows[4]).count(3)))
我想這凝結:
rows = [[convert[random.randint(0,7)] for _ in range(5)] for _ in range(5)]
cols = list(zip(*rows))
printedrows = ["\n"+ "[X]"*5 + " <- V: {} TOTAL: {}".format(row.count(0), sum(row)) for row in rows]
printcolvolt = ["V:{}".format(col.count(0) for col in cols)]
printcolcount = ["T:{}".format(sum(col) for col in cols)]
numgood = numtiles - rows.count(0)
爲什麼我得到了在0x030116C0>錯誤? (我添加了上下文的代碼的其餘部分。)
只是你忘了'col.count(0)'和'sum(col)'之後的圓括號嗎? – pascalhein
「錯誤」不是錯誤,它是您打印生成器對象。 – roippi
當你'掛起'時,請按照[PEP 8](http://www.python.org/dev/peps/pep-0008/)中的格式指導進行操作。具體地說,使用一些空格並限制行長到79個字符,因此您的代碼更易於其他人閱讀。列表理解可以邏輯上分成多行來幫助可讀性。 – dawg