我正在尝试打印列表,删除项目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]
答案 0 :(得分:1)
Python在这里很有趣,所以您必须对他很清楚:D:
seals = [1,2,3,4,5,6,7,8,9]
for seal in seals[:]:
print(seals)
seals.pop(0)
或使用range
:
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]
答案 1 :(得分:1)
如果您打算pop
贬值直到没有其他值,则可以使用以下类似的代码将其写入代码中可能更清楚:
seals = [1,2,3,4,5,6,7,8,9]
while seals:
print(seals)
seals.pop(0)
这避免了在迭代相同列表时修改列表的问题。
如果您不想随便修改印章,则可以执行以下操作:
seals = [1,2,3,4,5,6,7,8,9]
for i, v in enumerate(seals):
print(seals[i:])
seals
在此结束时保持不变。