编辑:我愚蠢的逻辑超越了我。 none 只是理解调用的返回值。 好的,我正在用 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']
>>>
现在这告诉我 for elem in a: 获取下一个可迭代元素然后应用主体,而理解在实际执行函数中的代码之前以某种方式调用列表的每个元素上的函数,因此修改列表从函数 (pop) 引出 ]none, none, none]
这样对吗?这里发生了什么?
谢谢
最佳答案
您的test
函数没有return
语句,因此在列表理解中使用它会导致None
的列表。交互式 python 提示打印出最后一条语句返回的任何内容。
例子:
>>> def noop(x): pass
...
>>> [noop(i) for i in range(5)]
[None, None, None, None, None]
因此,在您的问题中,列表理解和 for
循环的工作方式确实没有区别。
关于python 列表理解 VS 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5871256/