【发布时间】:2019-09-05 02:12:35
【问题描述】:
Hey Stack Overflow 社区,
我正在尝试做一件简单的事情 - 从给定列表中弹出每个第 i 个元素并删除每个元素中的任何前导/尾随空格。
问题是 - list.pop(i) 函数返回 out of range 错误,每当我通过 for i in range (0, len(games_list)) 循环。
我能够通过使用list.pop(0) 而不是list.pop(i) 来解决这个问题。请帮助我理解原因。
实际代码如下。
我查看了 range 和 .pop() 函数指南,但没有给出问题的答案。
代码
games_list = [
' The Movie: The Game',
' The Legend of Corgi',
' Dinosaur Diner']
for i in range(0, len(games_list)):
temp = games_list.pop(0)
temp = temp.strip()
games_list.append(temp)
print (games_list)
我希望输出如下:
['The Movie: The Game', 'The Legend of Corgi', 'Dinosaur Diner']
【问题讨论】:
-
.pop从列表中删除一个项目,因此当您继续迭代到列表的原始长度时,它会变小越过它的(新)端。 -
我无法使用您发布的代码或其中的
games_list.pop(i)重现该错误(尽管该版本没有正确剥离所有字符串)。您能否准确说明何时收到异常?显示实际损坏的代码,而不是修复您的固定代码?