cro*_*ant 5 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']
>>>
Run Code Online (Sandbox Code Playgroud)
现在这告诉我,a中的for elem获取下一个iteratable元素然后应用body,而在实际执行函数中的代码之前,理解以某种方式调用列表中每个元素的函数,因此从函数中修改列表(pop)导致] none,none,none]
这是正确的吗?这里发生了什么?
谢谢
您的test函数没有return语句,因此在列表理解中使用它会产生 s 列表None。交互式 python 提示符会打印出最后一条语句返回的内容。
例子:
>>> def noop(x): pass
...
>>> [noop(i) for i in range(5)]
[None, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
for所以实际上,问题中的列表理解和循环的工作原理没有什么区别。