【发布时间】: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