附加在Python名单 [英] Append of lists in Python

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

问题描述

名单的蟒蛇一个奇怪的追加。

A strange append of list in python.

在这里,我定义的类

class test:
    group = []
    def __init__(self,name):
    self.name = str(name)

然后我写那些

test0 = test(0)
test1 = test(1)
test_list = [test0, test1]

我要救 test1.name test0.group

test_list[0].group.append(test_list[1].name)

我打印test0.group,这是['1'],一切都OK。
但是,当我要救test0.name到test1.group

I print test0.group , it's ['1'] , everything is OK. But while I want to save test0.name into test1.group

test_list[1].group.append(test_list[0].name)

然后我打印 test1.group ,这是 ['1','0'] 。我不知道为什么它不是 [0]
顺便说一句,我在这里打印 test0.group ,它也是 ['1','0']

Then I print test1.group , it's ['1','0']. I don't know why it isn't ['0']? By the way, here I print test0.group , it's also the ['1','0'].

推荐答案

这是因为变量是由类<$ C $的所有实例共享变量C>测试,因此 TEST0 测试1 共享同一组。当你第一次追加即 1 它是好的,但是当你做你追加到同一个列表,因此它成为第二个追加 ['1','0'] 。事实上,如果打印 test0.group 为您的code的最后一行,你会看到,它也是 ['1' 0] ,因为它们是相同的变量。我不知道你想达到什么样的,但如果你想单独的组,那么你应该让他们 self.group ,而不是与它们移动到 __ init__ 方法。如果你能重组你的问题,我也许可以帮助你与你是什么样的实际努力实现。

That is because the group variable is a variable shared by all instances of the class test and therefore test0 and test1 share the same group. When you do the first append i.e. '1' it is fine but when you do the second append you are appending to the same list and therefore it becomes ['1', '0']. In fact, if you print test0.group as the last line of your code, you will see that it also is ['1', '0'] because they are the same variable. I am not sure what you are trying to achieve but if you want separate groups then you should make them self.group instead and move them into the __init__ method. If you can rephrase your question, I can maybe help you with what you are actually trying to achieve.

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

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