缩短Python3.x中的重复代码?

缩短Python3.x中的重复代码?,python,python-3.x,Python,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(

我想我开始掌握这个窍门了。对于此代码:

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)
rows=[[convert[random.randint(0,7)]表示范围内(5)]表示范围内(5)]
cols=列表(zip(*行))

printedrows=[“\n”+“[X]”“*5+”好吧,你在第1行和第2行有一个
语法错误(在
格式调用中缺少右括号),并且在编辑文章时把它放在了错误的位置

printcolvolt = ["V:{}".format(col.count(0)) for col in cols]
                                          ^
否则,将为cols
中的col格式化生成器
col.count(0),而不是它生成的值

对于第三行,我想你应该有

numgood = sum(row.count(2) + row.count(3) for row in rows)
否则,您将试图计算在我假设的列表中有多少个零,这些列表将始终为零。我不知道
numtiles
是什么


注意:如果你说的是问题的实质(例如输入、预期输出、实际输出/错误),而不仅仅是“为什么这不起作用”,那会更有帮助。

你必须在所指的函数后面加上括号:

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)]

将创建一个
生成器对象
(您在…
处看到的
生成器对象)并尝试打印它,因为
中…的
在括号内。

是否只是您忘记了
列计数(0)
求和(列)
之后的括号?该错误"这不是一个错误,而是您打印了一个生成器对象。当您“掌握了诀窍”后,请遵循中的格式指南,特别是,使用一些空格并将行长度限制为79个字符,以便其他人更容易阅读您的代码。列表理解可以在逻辑上分为多行以帮助可读性。这是错误吗我。另外,我在发布之前编辑了我的代码,但忘记了重新复制,对不起。您将右括号放在了错误的位置,因此您正在格式化生成器而不是其结果!我将在我的答案中添加一个示例。