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

2024-10-01 07:49:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个类,其中包含第二个对象的列表和第二个对象的amount值的总和。这本身就是有效的。但是我需要按类别对它们进行分组,所以我创建了一个字典。不过,这似乎很简单,每当我将一个对象附加到一个列表时,它就会附加到字典中的所有列表。你知道吗

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)))

当我运行上面的代码时,我得到了foo的预期数量1和bar的预期数量2,但是这两个列表的len都是2,因为它们都包含b1和b2。你知道吗

我把类对象拿出来,同样的原则工作只是附加到列表的dict上,所以下面的工作

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

输出:

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

有没有办法让这个工作或更好的解决方案?你知道吗


Tags: 对象列表lenfoobaramountb2mydict
2条回答

我已经初始化了构造函数中的变量-

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)))

更改objA类的定义,以便变量是在实例之前定义的,而不是在类本身上定义的

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

相关问题 更多 >