Python附加并产生列表 [英] Python appending to and yielding a list

查看:58
本文介绍了Python附加并产生列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎么回事?为什么list(f(seq))返回除f产生的元素列表以外的内容?

What is going on here? Why does list(f(seq)) return something other than a list of the elements yielded by f?

>>> def f(seq):
...   a = []
...   for i in seq:
...     yield a
...     a.append(i)
...
>>> f([1,2,3])
<generator object f at 0x1066c7aa0>
>>> b = f([1,2,3])
>>> b.next()
[]
>>> b.next()
[1]
>>> b.next()
[1, 2]
>>> b.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> list(f([1,2,3]))
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

推荐答案

您已经在函数内部产生了对列表a的完整引用.调用list(f([1,2,3]))时,结果只是[a, a, a],而a的最终形式是[1, 2, 3].

You have yielded the entire reference to the list a inside the function. When list(f([1,2,3])) is called the result simply is [a, a, a], and the final form of a is [1, 2, 3].

如果您保存了f.next()调用的所有结果,则没有什么不同.

This is no different if you had saved all the results from the f.next() calls.

>>> v1 = b.next()
>>> v2 = b.next()
>>> v1
[1]
>>> v2
[1]
>>> v3 = b.next()
>>> v4 = b.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> v1
[1, 2, 3]

同样,这是正确的,因为产生了a并且与f函数中相同内部列表的引用相同.

Again, this is correct because a is yielded and is the same reference to the same internal list inside the function f.

这篇关于Python附加并产生列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆