我有一个字典附加到元组中的每一项,我有一个问题,字典是作为一个总数添加,而不是每个字典分别计数。请参见下面的代码:
nps_user_ranges_default = {
'promoters': [9, 10],
'passive': [7, 8],
'detractors': [1, 2, 3, 4, 5, 6],
'skipped': [-1]
}
data = [(1, 'blue'), (10, 'blue'), (9, 'blue'), (10, 'blue'),
(4, 'green'), (10, 'green'), (6, 'red'), (10, 'red'), (10, 'green')]
nps_categories = {
'promoters': 0,
'detractors': 0,
'passive': 0,
'skipped': 0
}
scores = defaultdict(dict)
for score, color in data:
scores.setdefault(color, []).append(score)
for color, score in scores.items():
scores[color] = (score, nps_categories)
for color, score in scores.items():
sc, nps_category = score[0], score[1]
for s in sc:
if s in nps_user_ranges_default['promoters']:
nps_category['promoters'] += 1
elif s in nps_user_ranges_default['detractors']:
nps_category['detractors'] += 1
elif s in nps_user_ranges_default['passive']:
nps_category['passive'] += 1
else:
nps_category['skipped'] += 1
print(scores)
# The issue I am seeing here is that all dictionaries are adding on top of each other.
# I can't seem to get it so they all operate separately.
我当前的结果:
defaultdict(<type 'dict'>, {'blue': ([1, 10, 9, 10], {'promoters': 6, 'passive': 0, 'skipped': 0, 'detractors': 3}), 'green': ([4, 10, 10], {'promoters': 6, 'passive': 0, 'skipped': 0, 'detractors': 3}), 'red': ([6, 10], {'promoters': 6, 'passive': 0, 'skipped': 0, 'detractors': 3})})
scores[color]
为每种颜色引用相同的dictnps_categories
。改为创建唯一副本相关问题 更多 >
编程相关推荐