我正在尝试打印列表,删除项目 0,然后再次打印列表中的所有项目。这非常简单,但它没有按我的预期工作。它无法完成所有列表项的 for 循环。
我尝试首先使用 del 和 pop() 方法在列表中使用 range 函数。这不起作用,所以我一直在使用列表并得到相同的结果。
seals = [1,2,3,4,5,6,7,8,9]
for seal in seals:
print(seals)
seals.pop(0)
Expected Result
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[6, 7, 8, 9]
[7, 8, 9]
[8, 9]
[9]
Actual Result
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
最佳答案
Python在这里很有趣,所以你必须对他非常清楚:D:
seals = [1,2,3,4,5,6,7,8,9]
for seal in seals[:]:
print(seals)
seals.pop(0)
或者使用范围
:
seals = [1,2,3,4,5,6,7,8,9]
for seal in range(len(seals)):
print(seals)
seals.pop(0)
两者都重现:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[6, 7, 8, 9]
[7, 8, 9]
[8, 9]
[9]
关于带有数字列表的 Python for 循环未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53966534/