【问题标题】:How to fix ".pop() function out of range"如何修复“.pop() 函数超出范围”
【发布时间】: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 从列表中删除一个项目,因此当您继续迭代到列表的原始长度时,它会变小越过它的(新)端。
  • Pop index out of range的可能重复
  • 我无法使用您发布的代码或其中的games_list.pop(i) 重现该错误(尽管该版本没有正确剥离所有字符串)。您能否准确说明何时收到异常?显示实际损坏的代码,而不是修复您的固定代码?

标签: python list


【解决方案1】:

您在迭代到原始长度时正在缩短列表,因为game_list.pop(i) 也会删除i 处的元素。

一般来说,迭代列表最好由 foreach 完成:

striped_games_list = []
for title in games_list:
    striped_games_list.append(title.strip())
game_titles = striped_games_list  # A better design would be to exclude this and simply use striped_game_list going forward

但是,在您的情况下,我建议您使用列表理解:

game_titles = [title.strip() for title in game_titles]

【讨论】:

  • 哦,现在我明白你和@JaredSmith 的意思了。我认为通过附加项目我不会更改列表。但是,我知道为什么会这样。感谢您的意见!
【解决方案2】:

您的代码非常非 Pythonic。您可以直接迭代列表的元素而不是它们的索引,并将剥离的元素收集到另一个干净的列表中,而不是弹出并附加到同一个列表中。这是否回答了您的问题:

' The Movie: The Game',
' The Legend of Corgi',
' Dinosaur Diner']

new_list = []
for temp in games_list:
    temp = temp.strip()
    new_list.append(temp)

print (new_list)

【讨论】:

  • 感谢您指出我的代码非常非 Pythonic! :/ 并感谢涉及 for ... in ...!:) 的解决方案 ~Cheers
  • 当有人指出您可以改进的地方时,您为什么会感到难过(:/ 事情)?有一个叫做 Pythonic 的概念,当某些东西没有真正遵循 Pythonic 方法(也就是非 Pythonic)时,这是非常标准的说法。
猜你喜欢
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 2021-01-27
  • 2013-06-16
  • 1970-01-01
相关资源
最近更新 更多