提问人:Steven Torman 提问时间:7/30/2022 最后编辑:John KugelmanSteven Torman 更新时间:7/30/2022 访问量:359
为什么当我向循环传递复制的列表时,我的循环会返回一个空列表错误,而原始列表却没有错误?[已结束]
Why does my loop return an empty list error when I pass it a copied list, but does not error with an original list? [closed]
问:
short_texts = ['I like the apple', 'I like the orange as well', 'Finally, I like the inside of a kiwi the best']
sent_messages = []
def send_messages(messages):
while messages:
popped_st = short_texts.pop(0)
print(popped_st)
sent_messages.append(popped_st)
send_messages(short_texts[:])
print(short_texts)
print(sent_messages)
错误>
I like the apple
I like the orange as well
Finally, I like the inside of a kiwi the best
Traceback (most recent call last):
File "C:\Users\Steve\Documents\python_work\8.11.py", line 13, in <module>
send_messages(short_texts[:])
File "C:\Users\Steve\Documents\python_work\8.11.py", line 8, in send_messages
popped_st = short_texts.pop(0)
IndexError: pop from empty list
[Finished in 200ms]
如果我去掉函数调用的 slice 参数,程序就会工作。添加切片会导致“从空列表中弹出”。
我正在阅读 Python 速成课程 2E,在练习 8.10.py 中,它要求我将初始列表的副本传递给函数并打印附加列表和原始列表。
显然我在这里没有掌握一个概念?
答:
0赞
Barmar
7/30/2022
#1
你没有在循环中修改,所以条件永远不会改变,你有一个无限循环。你应该从 中弹出,而不是 。然后最终会变为空,条件将为 false,循环停止。messages
while messages:
messages
short_texts
messages
while messages:
def send_messages(messages):
while messages:
popped_st = messages.pop(0)
print(popped_st)
sent_messages.append(popped_st)
当您不使用切片来调用函数时,它会起作用,因为然后引用相同的列表。在这种情况下,等价于 。切片将创建列表的副本。messages
short_texts
short_texts.pop(0)
messages.pop(0)
评论
IndexError: pop from empty list
while messages:
True
messages
是 的副本。所以不修改,循环是无限的。short_texts
short_texts.pop()
messages