python list comprehension VS for behavior

时间:2011-05-03 14:43:09

标签: python list-comprehension

编辑:我的愚蠢逻辑领先于我。没有一个只是理解呼叫的回报。 好吧,我在python中运行了一些测试,并且我在执行命令方面遇到了一些差异,这让我了解它是如何实现的,但是我想让你好好运行它来看看如果我是对的,或者还有更多的东西。请考虑以下代码:

>>> a = ["a","b","c","d","e"]
>>> def test(self,arg):
...     print "testing %s" %(arg)
...     a.pop()
... 
>>>[test(elem) for elem in a]
testing a
testing b
testing c
[None, None, None]
>>> a
['a', 'b']
#now we try another syntax
>>> a = ["a","b","c","d","e"]
>>> for elem in a:
...     print "elem is %s"%(elem)
...     test(elem)
... 
elem is a
testing a
elem is b
testing b
elem is c
testing c
>>> a
['a', 'b']
>>> 

现在这告诉我a中的for elem获取下一个iteratable元素然后应用body,而在实际执行函数中的代码之前,理解以某种方式调用列表中每个元素的函数,因此修改列表从函数(pop)导致] none,none,none]

这是对的吗?这里发生了什么?

谢谢

3 个答案:

答案 0 :(得分:4)

您的test函数没有return语句,因此在列表推导中使用它会产生None列表。交互式python提示符打印出最后一个语句返回的内容。

示例:

>>> def noop(x): pass
... 
>>> [noop(i) for i in range(5)]
[None, None, None, None, None]

所以,你的问题中列表理解和for循环的工作原理没有区别。

答案 1 :(得分:1)

>>> a = ["a","b","c","d","e"]
>>> i = iter(a)
>>> next(i)
'a'
>>> a.pop()
'e'
>>> next(i)
'b'
>>> a.pop()
'd'
>>> next(i)
'c'
>>> a.pop()
'c'
>>> next(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

答案 2 :(得分:0)

它必须"c",然后用完列表中的元素。如果test没有返回任何内容,则会获得[None, None, None]