【问题标题】:Pop from empty list errors [closed]从空列表错误中弹出[关闭]
【发布时间】:2014-04-04 02:50:21
【问题描述】:

我正在编写一个从包含 3 个嵌套列表的列表中弹出的代码。 我想从第一个内部循环的末尾开始弹出最后一个元素。它工作正常,直到它到达第一个元素并返回(IndexError:从空列表中弹出)。如何使用 range 函数处理这种情况?

toappendlst= [[[62309, 1, 2], [62309, 4, 2], [6222319, 4, 2], [6235850, 4, 2], [82396378, 4, 3], [94453486, 4, 3], [0, 0, 0]],[[16877135, 6, 2], [37247278, 7, 2],    [47671207, 7, 2], [0, 0, 0]]]

for chro in range(-1,len(toappendlst)):
            popdPstn = toappendlst[chro].pop()
            print(popdPstn)

O\P

[0, 0, 0]
[47671207, 7, 2]
[37247278, 7, 2]
Traceback (most recent call last):
 File "C:\Python33\trial.py", line 41, in <module>
 popdPstn = toappendlst[chro].pop()
IndexError: pop from empty list

【问题讨论】:

  • 使用range(len(toappendlst))。更优选地简单地迭代列表:for lst in toappendlst: popdPstn = lst.pop() ...
  • 无法复制。您发布的代码打印不同的东西,并且不会抛出错误。
  • 我觉得这个问题应该结束了。

标签: python list loops nested


【解决方案1】:

用....更改您的列表

toappendlst= [[[62309, 1, 2]], [[62309, 4, 2]], [[6222319, 4, 2]], [[6235850, 4, 2]], [[82396378, 4, 3]], [[94453486, 4, 3]], [[0, 0, 0]],[[16877135, 6, 2]], [[37247278, 7, 2]],    [[47671207, 7, 2]], [[0, 0, 0]]]

或者你可以使用一个序列作为列表...

toappendlst= [[62309, 1, 2], [62309, 4, 2], [6222319, 4, 2], [6235850, 4, 2], [82396378, 4, 3], [94453486, 4, 3], [0, 0, 0],[16877135, 6, 2], [37247278, 7, 2],    [47671207, 7, 2], [0, 0, 0]]
for chro in toappendlst[::-1]:
        print(chro)

【讨论】:

  • 我不必使用列表,因为这只是一个测试列表,但我将从 txt 文件输入。
  • 好的,然后 toappendlst[::-1] 正在为您的列表工作。
  • 它确实有效。谢谢@ajay。这对我来说是新的。
  • 它确实有效。谢谢@ajay。这对我来说是新的。你能简单解释一下这个结构代表什么吗?
  • 是的,它在 python 中调用切片。语法:list[start_position:end_position:(optional)step] step 具有像 1,2,... 这样的数值,而负值则以相反的顺序迭代列表。
【解决方案2】:

您正在迭代range(-1, len(lst)),这是一个len(lst)+1 数字范围(-1 到len(lst)-1 包括在内)。这超过了列表中元素的数量,因此您的最终 .pop 在一个空列表上运行。

您可能不需要真正从列表中弹出。例如,for item in reversed(lst): 将以相反的顺序遍历列表(与您从列表中弹出的顺序相同),而不会破坏列表内容。

或者,如果您真的需要从列表中弹出每个项目,则只需迭代 for i in xrange(len(lst)) 以迭代 len(lst) 次。如果您需要相反顺序的索引,for i in reversed(xrange(len(lst)))

【讨论】:

  • 谢谢@nneonneo .. 我已经修复了第一个案例。我不必从(-1)开始。我需要弹出,因为 toappendlst 是输入列表,我要将弹出的值插入到外部。我为处理这种情况所做的是添加一个 while 循环。 outerlst = [] for chrom in range(len(toappendlst)): outerlst.append([]) while (len(toappendlst[chrom]) > 0 ): popdPstn = toappendlst[chrom].pop()
猜你喜欢
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
相关资源
最近更新 更多