用Python压缩重复代码?

2024-10-03 15:23:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如何浓缩这些?在

col1 = [row1[0],row2[0],row3[0],row4[0],row5[0]]
col2 = [row1[1],row2[1],row3[1],row4[1],row5[1]]
col3 = [row1[2],row2[2],row3[2],row4[2],row5[2]]
col4 = [row1[3],row2[3],row3[3],row4[3],row5[3]]
col5 = [row1[4],row2[4],row3[4],row4[4],row5[4]]

printedxrow1 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row1.count(0))+"  TOTAL: "+str(sum(row1))]
printedxrow2 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row2.count(0))+"  TOTAL: "+str(sum(row2))]
printedxrow3 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row3.count(0))+"  TOTAL: "+str(sum(row3))]
printedxrow4 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row4.count(0))+"  TOTAL: "+str(sum(row4))]
printedxrow5 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row5.count(0))+"  TOTAL: "+str(sum(row5))]

我主要是不确定如何停止不断变化的变量的重复。谢谢。在


Tags: countcol2col3col1totalsumrow1row2
2条回答
col1 = [row1[0],row2[0],row3[0],row4[0],row5[0]]
col2 = [row1[1],row2[1],row3[1],row4[1],row5[1]]
col3 = [row1[2],row2[2],row3[2],row4[2],row5[2]]
col4 = [row1[3],row2[3],row3[3],row4[3],row5[3]]
col5 = [row1[4],row2[4],row3[4],row4[4],row5[4]]

以上行可以替换为:

^{pr2}$
>>> zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
<zip object at 0x0000000002B17FC8>
>>> col1, col2, col3 = zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
>>> col1
(1, 4, 7)
>>> col2
(2, 5, 8)
>>> col3
(3, 6, 9)

^{}。在

rows = [row1,row2,row3,row4,row5]  # you'd generate rows in a cleaner way    

cols = list(zip(*rows))

printedxrows = [ ("[X]","[X]","[X]","[X]","[X]","  <- V: {}   TOTAL: {}"
                                               .format(row.count(0), sum(row)))
                 for row in rows ]

注意,为了更好的可读性,我还将它作为一个格式字符串。在

相关问题 更多 >