为什么这个python生成器每次都返回相同的值? [英] Why is this python generator returning the same value everytime?

查看:111
本文介绍了为什么这个python生成器每次都返回相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个生成列表的生成器:

I have this generator that yields lists:

def gen():
    state = [None]

    for i in range(5):
        state[0] = i
        yield state

这是我叫它的输出:

>>> list(gen())
[[4], [4], [4], [4], [4]]

为什么所有元素都是[4]?是不是[[0], [1], [2], [3], [4]]?

Why are all the elements [4]? Shouldn't it be [[0], [1], [2], [3], [4]]?

推荐答案

您正在重用同一列表对象.生成器一遍又一遍地返回一个对象,对其进行操作,但是对该对象的任何其他引用都会看到相同的变化:

You are reusing the same list object. Your generator returns the one object over and over again, manipulating it as it goes, but any other references to it see those same changes:

>>> r = list(gen())
>>> r
[[4], [4], [4], [4], [4]]
>>> r[0] is r[1]
True
>>> r[0][0] = 42
>>> r
[[42], [42], [42], [42], [42]]

获取列表的副本或创建一个新的新鲜列表对象,而不是对其进行操作.

Yield a copy of the list or create a new fresh list object instead of manipulating one.

def gen_copy():
    state = [None]

    for i in range(5):
        state[0] = i
        yield state.copy()  # <- copy

def gen_new():
    for i in range(5):
        state = [i]  # <- new list object every iteration
        yield state

这篇关于为什么这个python生成器每次都返回相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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