【问题标题】:appending to a list of objects within a dictionary of objects in python附加到python中对象字典中的对象列表
【发布时间】:2020-04-18 09:19:37
【问题描述】:

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

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。

我取出了类对象,相同的主要工作只是附加到列表的字典中,所以以下工作

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

输出:

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

有没有办法让它工作或更好的解决方案?

【问题讨论】:

  • objA.listBs 已在类本身上定义。每次您从 objA 的任何实例中引用 listBs 时,都会引用同一个列表
  • @IainShelvington 如何实现所需的行为,让每个 objA 实例都有自己的 listBs?还有其他我不知道的定义方式吗?

标签: python list class dictionary


【解决方案1】:

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

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

【讨论】:

  • 我刚刚意识到我忘记将其标记为正确答案。感谢您的帮助。
【解决方案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)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多