我正在尝试遍历 2D 列表,并取决于因素,附加到行或删除整行
如果tempX
匹配某个值,tempX
并且tempY
应该追加到列表中的当前行。如果tempX
与该值不匹配,则应从列表中删除整行。
这是到目前为止的代码。
aList = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
i = 0
for a, b, c, d, e in aList[:]:
tempC = c
tempD = D
tempX = tempC * 2 # These are just a placeholders for another calculation
tempY = tempD * 2
if tempX <= 10:
aList[i].append(tempX)
aList[i].append(tempY)
else:
del aList[i]
i += 1
预期结果: aList = [[6, 7, 8, 9, 10, 16, 18], [11, 12, 13, 14, 15, 26, 28]]
相反,这会导致
ValueError: too many values to unpack
编辑
经过一番研究,我得出了这个解决方案。
关键是bList = aList[::-1]
;这将列表拼接成相反的顺序,消除了前面示例中的情况,即我有效地试图在没有千斤顶的情况下从汽车上取下轮胎。
aList = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25],[26,27,28,29,30]]
bList = aList[::-1]
i = 0
for a, b, c, d, e in bList:
tempC = c
tempD = d
tempX = tempC * 2
tempY = tempD * 2
if tempX >= 50:
bList[i].append(tempX)
bList[i].append(tempY)
else:
del bList[i]
i += 1
print bList
这将是一个很好的解决方案,除了它每隔两行跳过一次。我不太确定是什么导致它跳过行。
[[26, 27, 28, 29, 30, 56, 58], [21, 22, 23, 24, 25], [16, 17, 18, 19, 20], [11, 12, 13, 14, 15], [6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
[[26, 27, 28, 29, 30, 56, 58], [16, 17, 18, 19, 20], [11, 12, 13, 14, 15], [6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
[[26, 27, 28, 29, 30, 56, 58], [16, 17, 18, 19, 20], [6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
[[26, 27, 28, 29, 30, 56, 58], [16, 17, 18, 19, 20], [6, 7, 8, 9, 10]]
预期结果: bList = [[26, 27, 28, 29, 30, 56, 58]]
应删除所有其他行