python 列表理解 VS 行为
编辑:我的愚蠢逻辑超越了我。 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']
>>>
现在,这告诉我 a: 中的 for elem 获取下一个可迭代元素,然后应用主体,而推导式在实际执行函数中的代码之前以某种方式调用列表中每个元素上的函数,因此修改函数 (pop) 中的列表导致]none, none, none]
这是对的吗?这里发生了什么?
谢谢
EDIT: stupid logic of mine got ahead of me. The none are just the returns from the comprehension call.
Ok, I'm running some tests in python, and I ran into a bit of a difference in execution orders, which leads me to an understanding of how it is implemented, but I'd like to run it by you fine people to see if I'm right or there is more to it. Consider this code:
>>> 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']
>>>
Now this tells me that the for elem in a: gets the next iteratable element then applies the body, whereas the comprehension somehow calls the function on each element of the list before actually executing the code in the function, so modifying the list from the function ( pop) leads to the ]none, none, none]
Is this right? what is happening here?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
test
函数没有return
语句,因此在列表理解中使用它会产生None
列表。交互式 python 提示符会打印出最后一条语句返回的内容。示例:
实际上,问题中的列表理解和
for
循环的工作原理没有什么区别。Your
test
function has noreturn
statement, thus using it in a list comprehension results in a list ofNone
s. The interactive python prompt prints out whatever the last statement returns.Example:
So really there's no difference in how the list comprehension and
for
loop in your question work.它已经到达
“c”
,然后耗尽了列表中的元素。由于test
不返回任何内容,因此您会得到[None, None, None]
。It has got to
"c"
, then ran out of elements in the list. Astest
returns nothing, you get[None, None, None]
.