Python中的Condensing Repetitive Code?

时间:2013-12-10 15:55:34

标签: python python-3.x

如何压缩这些?

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

我主要只是不确定如何通过更改变量来停止重复。感谢。

2 个答案:

答案 0 :(得分:4)

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

以上行可以替换为:

col1, col2, col3, col4, col5 = zip(row1, row2, row3, row4, row5)

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

请参阅zip

答案 1 :(得分:1)

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 ]

注意我还使它成为一个格式字符串,以提高可读性。