Python列表追加导致奇怪的结果 [英] Python list append causes strange result

查看:68
本文介绍了Python列表追加导致奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很奇怪的问题.这是示例代码:

I have really strange problem. Here is the sample code:

class SomeClass(object):
    a = []
    b = []
    def __init__(self, *args, **kwargs):
        self.a = [(1,2), (3,4)]
        self.b = self.a
        self.a.append((5,6))
        print self.b

SomeClass()

打印输出[[(1,2),(3,4),(5,6)],但是为什么,为什么结果不是[(1,2,3,4,3)]? 您知道我如何在self.b中拥有self.a的旧值吗?

Print outputs [(1, 2), (3, 4), (5, 6)], but why, why result isn't [(1,2), (3,4)] ? Do you know how can I have the old value of self.a in self.b?

谢谢!

推荐答案

您要为self.b(而不是副本)分配相同的列表.

You are assigning the same list to self.b, not a copy.

如果要self.b引用列表的副本,请使用list()或完整切片创建一个副本:

If you wanted self.b to refer to a copy of the list, create one using either list() or a full slice:

self.b = self.a[:]

self.b = list(self.a)

您可以从交互式解释器轻松地对此进行测试:

You can test this easily from the interactive interpreter:

>>> a = b = []  # two references to the same list
>>> a
[]
>>> a is b
True
>>> a.append(42)
>>> b
[42]
>>> b = a[:]  # create a copy
>>> a.append(3.14)
>>> a
[42, 3.14]
>>> b
[42]
>>> a is b
False

这篇关于Python列表追加导致奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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