>>> 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]
这是对的吗?这里发生了什么?
谢谢
答案 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]
。