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属性的所有实例之后。
获得理想结果的最佳方法是什么?