2013-12-11 29 views
0

我想我已經開始掌握了這一點。對於此代碼:縮短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>錯誤? (我添加了上下文的代碼的其餘部分。)

+2

只是你忘了'col.count(0)'和'sum(col)'之後的圓括號嗎? – pascalhein

+1

「錯誤」不是錯誤,它是您打印生成器對象。 – roippi

+0

當你'掛起'時,請按照[PEP 8](http://www.python.org/dev/peps/pep-0008/)中的格式指導進行操作。具體地說,使用一些空格並限制行長到79個字符,因此您的代碼更易於其他人閱讀。列表理解可以邏輯上分成多行來幫助可讀性。 – dawg

回答

1

那麼你有一個SyntaxError(在format調用缺少右括號)在第1和第2行,並且編輯你的帖子時把它放在錯誤的地方。

printcolvolt = ["V:{}".format(col.count(0)) for col in cols] 
             ^

否則,你格式化發電機col.count(0) for col in cols本身,而不是它生成的值。

對於3號線,我想你應該有類似

numgood = sum(row.count(2) + row.count(3) for row in rows) 

否則,您要統計有多少個零有什麼我以爲是一個列表的列表,這將永遠給予零。我不知道numtiles是什麼。

N.B.如果你說實際存在的問題(如投入,預期產出,實際產出/錯誤)而不僅僅是「爲什麼不這樣做」,那將會更有幫助。

+0

<發生器對象在0x030116C0>是它給我的錯誤。另外,我在發佈之前編輯了我的代碼,並忘記重新複製,對不起。 – Kweb123

+0

您已將右括號放在錯誤的地方,以便格式化發生器而不是其結果!我會在我的答案中舉一個例子。 – jonrsharpe

0

你有你指的是功能之後加括號:

printcolvolt = ["V:{}".format(col.count(0)) for col in cols] 
printcolcount = ["T:{}".format(sum(col)) for col in cols] 

否則,

#WRONG 
printcolvolt = ["V:{}".format(col.count(0) for col in cols)] 

將創建一個generator object(你有generator object <genexpr> at ...看到),並嘗試打印這是因爲for ... in位於括號內。