【发布时间】:2026-01-21 08:00:01
【问题描述】:
今天刚开始学习 Python。我很喜欢它,文档就像人们所说的那样有帮助。但很明显,我对 Python 的两个特性没有了解:那些列表和那些 for 循环。
这段代码的结果:
lets = ['a','b','c','d','e','f','g','h','i','j']
for j in lets:
del lets[0]
print(lets)
这是:
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['d', 'e', 'f', 'g', 'h', 'i', 'j']
['e', 'f', 'g', 'h', 'i', 'j']
['f', 'g', 'h', 'i', 'j']
为什么它在五步而不是十步处停止(因此删除所有项目)?
【问题讨论】:
-
嗯,你正在迭代一个列表,当你迭代它时你正在删除它。好像你不想那样做。