Python在2D列表中循环,要么向当前行追加值,要么删除i

2024-09-20 23:00:48 发布

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

我正在尝试遍历一个2D列表,并依赖于因子,要么追加到行,要么移除整个行

如果tempX与某个值匹配,tempX和{}应该追加到列表中的当前行。{t>如果该值与^不匹配,则应从列表中删除整行。在

这是目前为止的代码。在

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

相反,这会导致

^{pr2}$

编辑

经过一番研究,我找到了这个解决方案。在

关键是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]]所有其他行都应删除


Tags: in列表forif情况解决方案elsedel
1条回答
网友
1楼 · 发布于 2024-09-20 23:00:48

不要偏离你的代码太远。。。在

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

i = 0

for a, b, c, d, e in aList:
    tempC = c
    tempD = d

    tempX = tempC * 2
    tempY = tempD * 2

    if tempX >= 50:
        bList.append(aList[i]+ [tempX,tempY])
    i += 1

print bList

相关问题 更多 >

    热门问题