在 Python 中追加列表 [英] Append of lists in Python

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

问题描述

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'] ,一切正常.但是虽然我想将 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'].

推荐答案

那是因为 group 变量是 test 类的所有实例共享的变量,因此test0test1 共享同一个组.当您执行第一次追加时,即 '1' 没问题,但是当您执行第二次追加时,您将追加到同一个列表中,因此它变为 ['1', '0'].事实上,如果你打印 test0.group 作为代码的最后一行,你会看到它也是 ['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天全站免登陆