每次迭代更新字典,n

2024-09-30 00:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典附加到元组中的每一项,我有一个问题,字典是作为一个总数添加,而不是每个字典分别计数。请参见下面的代码:

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})})

Tags: indefaultgreenbluecolorscorepassiveranges
1条回答
网友
1楼 · 发布于 2024-09-30 00:31:47

scores[color]为每种颜色引用相同的dictnps_categories。改为创建唯一副本

for color, score in scores.items():
    scores[color] = (score, nps_categories.copy())

相关问题 更多 >

    热门问题