【问题标题】:Incomplete list pop in list comprehention列表理解中的不完整列表弹出
【发布时间】:2016-10-18 12:16:28
【问题描述】:

我一直在尝试使用takewhile 函数来理解列表中的pop 元素,但我遇到了一些我很难理解的事情。我的终端会话如下所示:

但是,当我用字符串尝试同样的事情时,问题并没有发生:

有人可以向我解释第一个场景中发生的情况吗?为什么g.pop(0) 只返回了[1, 2]

用于复制的成绩单(为什么 Stack 没有可折叠部分):

>>> from itertools import takewhile
from itertools import takewhile
>>> g = [1,2,3,4,5]
>>> [a for a in takewhile(lambda x: x < 4, g)]
[1, 2, 3]
>>> [g.pop() for _ in takewhile(lambda x: x < 4, g)]
[5, 4, 3]
>>> g = [1,2,3,4,5]
>>> [g.pop(0) for _ in takewhile(lambda x: x < 4, g)]
[1, 2]

>>> g = ['1', '2', '3', '4', '5']
>>> [a for a in takewhile(lambda x: x != '4', g)]
['1', '2', '3']
>>> [g.pop() for _ in takewhile(lambda x: x != '4', g)]
['5', '4', '3']
>>> g = ['1', '2', '3', '4', '5']
>>> [g.pop(0) for _ in takewhile(lambda x: x != '4', g)]
['1', '2', '3']

【问题讨论】:

    标签: python python-2.7 list list-comprehension


    【解决方案1】:

    我想通了,因为我尝试使用deque,它引发了RuntimeError: deque mutated during iteration

    执行如下:

    1. g[0] = 1 &lt; 4; g.pop(0) =&gt; 1
    2. g[1] = 3 &lt; 4; g.pop(0) =&gt; 2
    3. g[2] = 5 &gt; 4; break

    这也解释了为什么它在第二种情况下工作,因为在迭代期间 '4' 没有被击中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-10
      • 2021-03-15
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      相关资源
      最近更新 更多