Python-附加到对象列表中的对象列表中

时间:2019-12-12 11:18:09

标签: python list object append

采用以下示例:

from pprint import pprint
class ResultsClass:
    def __init__(self, 
    name = None, 
    counts = []): 
        self.name = name
        self.counts = counts

objs = [ResultsClass() for i in range(5)]
i = 0 
while i < 4:
    objs[i].counts.append("count is " + str(i))
    pprint(objs[i].counts)
    i = i+1

结果是:

['count is 0']
['count is 0', 'count is 1']
['count is 0', 'count is 1', 'count is 2']
['count is 0', 'count is 1', 'count is 2', 'count is 3']

我也尝试了以下代码,但无济于事:

i = 0
objs = [ResultsClass() for i in range(5)]
for obj in objs:
    obj.counts.append("count is " + str(i))
    pprint(obj.counts)
    i = +1

我想做的是让每个ResultsClass实例具有不同的 counts 列表,如下所示:

['count is 0'] 
['count is 1'] 
['count is 2'] 
['count is 3']

从PowerShell的背景来看,我本来以为Python会遍历对象的每个实例并将其追加到其中的特定列表中。相反,它似乎是附加到对象列表和 counts 属性的所有实例之后。

达到预期结果的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

from pprint import pprint
class ResultsClass:
    def __init__(self, 
    name = None): 
        self.name = name
        self.counts = []

objs = [ResultsClass() for i in range(5)]
i = 0 
while i < 4:
    objs[i].counts.append("count is " + str(i))
    pprint(objs[i].counts)
    i = i+1