带有数字列表的 Python for 循环未按预期工作

标签 python

我正在尝试打印列表,删除项目 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/

相关文章:

python - 子类化对象导致 NoneType

python - 如何获取有序的字符串列表

python - Matplotlib制作不重叠气泡图(圆圈堆积)

python - 在 tkinter 中查找窗口的坐标

python - session cookie 太大 flask 应用程序

python - Dask 数据框中的多个聚合用户定义函数

python - 如何根据列表中的键对元组列表进行排序?

python - 如何使用 Pscycopg2 将字典插入 Postgresql 表

python - 为什么 scipy.linalg 的方法在 9x9 矩阵上运行速度较慢?

python - Numpy:根据密度函数生成网格