简体   繁体   English

附加到python中对象字典中的对象列表

[英]appending to a list of objects within a dictionary of objects in python

I am creating a class that has a list of a second object and a total of the amount value from the second object.我正在创建一个类,该类具有第二个对象的列表和来自第二个对象的金额值的总和。 This in itself works.这本身就有效。 However I need to group them by category so I created a dictionary of them.但是我需要按类别对它们进行分组,所以我创建了一个字典。 Which seems simple however whenever I append an object to a list it appends to all of the lists in the dictionary.这看起来很简单,但是每当我将一个对象附加到一个列表时,它就会附加到字典中的所有列表中。

class objA:
    amount = 0
    listBs = []
    category = ""
    def __init__(self,category):
        self.category = category
class objB:
    amount = 0
    category = ""
    otherproperty = ""

mydict = {}

b1 = objB()
b1.amount = 1
b1.category = "foo"
b1.otherproperty = "abc"

if(b1.category not in mydict.keys()):
    mydict[b1.category] = objA(b1.category)
mydict[b1.category].listBs.append(b1)
mydict[b1.category].amount += b1.amount


b2 = objB()
b2.amount = 2
b2.category = "bar"
b2.otherproperty = "xyz"

if(b2.category not in mydict.keys()):
    mydict[b2.category] = objA(b2.category)
mydict[b2.category].listBs.append(b2)
mydict[b2.category].amount += b2.amount

print("foo amount: " + str(mydict["foo"].amount) + " - foo len: " + str(len(mydict["foo"].listBs)))
print("bar amount: " + str(mydict["bar"].amount) + " - bar len: " + str(len(mydict["bar"].listBs)))

when I run the above code I get the expected amount of 1 for foo and 2 for bar but both lists have a len of 2 since they both contain b1 and b2.当我运行上面的代码时,我得到了预期的 1 为 foo 和 2 为 bar 但两个列表的 len 都是 2,因为它们都包含 b1 和 b2。

I took the class objects out and the same pricipal works just appending to a dict of lists so the following works我把类对象取出来,同样的主要工作只是附加到列表的字典中,所以以下工作

dictoflists = {}
dictoflists["key1"] = []
dictoflists["key1"].append("k1v1")
dictoflists["key2"] = []
dictoflists["key2"].append("k2v1")
dictoflists["key2"].append("k2v2")
print(dictoflists)

output:输出:

{'key1': ['k1v1'], 'key2': ['k2v1', 'k2v2']}

Is there a way to get this to work or a better solution?有没有办法让它工作或更好的解决方案?

Change the definition of the objA class so that the variables are defined pre-instance instead of on the class itself更改objA类的定义,以便在实例之前而不是在类本身上定义变量

class objA:
    def __init__(self, category):
        self.category = category
        self.amount = 0
        self.listBs = []

So, I have initialized the variable inside constructor -所以,我已经在构造函数中初始化了变量 -

class objA:
        amount = 0

        category = ""
        def __init__(self,category):
            self.category = category
      #Initialize the variable inside constructor     
            self.listBs = []
class objB:
    amount = 0
    category = ""
    otherproperty = ""

mydict = {}

b1 = objB()
b1.amount = 1
b1.category = "foo"
b1.otherproperty = "abc"

if(b1.category not in mydict.keys()):
    mydict[b1.category] = objA(b1.category)
mydict[b1.category].listBs.append(b1)
mydict[b1.category].amount += b1.amount


b2 = objB()
b2.amount = 2
b2.category = "bar"
b2.otherproperty = "xyz"

if(b2.category not in mydict.keys()):
    mydict[b2.category] = objA(b2.category)
mydict[b2.category].listBs.append(b2)
mydict[b2.category].amount += b2.amount

print("foo amount: " + str(mydict["foo"].amount) + " - foo len: " + str(len(mydict["foo"].listBs)))
print("bar amount: " + str(mydict["bar"].amount) + " - bar len: " + str(len(mydict["bar"].listBs)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM