如果此列表是某个对象的属性,如何将数据添加到列表中

时间:2017-11-10 13:25:12

标签: python list

我有一个对象

class Lists:
    pass

for item in items_list:
    name = str(item.theme)
    if hasattr(Lists, name):
        setattr(Lists, name, [])
        append(value) to this array

    else:
        setattr(Lists, name, [])

如果此对象具有此属性,我只将值附加到此列表。 否则,我想将此属性添加到对象,然后将值附加到此列表。

2 个答案:

答案 0 :(得分:1)

您可以使用setattr + getattr。这是一个小例子。

class A:
    pass
attr = ['foo', 'bar', 'baz', 'foo', 'foo', 'baz']
vals = range(len(attr))

for i, j in zip(attr, vals):
     if not hasattr(A, i):
         setattr(A, i, [])  # the attribute is created if it didn't already exist

     getattr(A, i).append(j)
vars(A)     
mappingproxy({..., 'bar': [1], 'baz': [2, 5], 'foo': [0, 3, 4]})

答案 1 :(得分:0)

要向对象添加属性,请使用:

Lists.name = lambda: None

您的代码现在看起来像:

class Lists:
    pass   

for item in items_list:
    name = str(item.theme)
    if hasattr(Lists, name):
        setattr(Lists, name, [])
        append(value) to this array

    else:
        Lists.name = lambda: None
        setattr(Lists, name, [])