gpt4 book ai didi

python - 在 Python 中压缩重复代码?

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:18 24 4
gpt4 key购买 nike

压缩这些的方法?

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

我主要是不确定如何停止更改变量的重复。谢谢。

最佳答案

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 .

关于python - 在 Python 中压缩重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20499067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com