在Python3中找出字典时遇到了麻烦

时间:2018-04-10 06:53:12

标签: python-3.x

Python字典,我想得到元素的数量。 所以,如果我的字典是:

my_dict= {
    ...
'Barbara': ['blue', 5],
'Betty': ['purple', 8],
'Brian': ['orange', 7],
'Carol': ['green', 1],
'Charles': ['green', 9],
'Christopher': ['pink', 2],
'Cynthia': ['blue', 1],
'Daniel': ['blue', 10],
'David': ['purple', 7],
'Deborah': ['red', 6],
'Donald': ['gray', 7],
...

}

因此它包含名称,颜色和数字,我正在寻找如何对其进行编码以便我可以计算每种颜色和数字(1到10)的实例,因此对于此摘录,输出可能是:

(color:        instances,)

(blue:            3)
(purple:          2)
(orange: 1)
(green: 2)
(pink: 1)
(red: 1)
(gray: 1)

(numbers: instances)

(1: 2)
(2: 1)
(3: 0)
(4: 0)
(5: 1)
(6: 1)
(7: 3)
(8: 0)
(9: 1)
(10: 1)

2 个答案:

答案 0 :(得分:2)

以下是使用内置模块Counter

中的collections数据结构的解决方案
from collections import Counter    

my_dict= {
    'Barbara': ['blue', 5],
    'Betty': ['purple', 8],
    'Brian': ['orange', 7],
    'Carol': ['green', 1],
    'Charles': ['green', 9],
    'Christopher': ['pink', 2],
    'Cynthia': ['blue', 1],
    'Daniel': ['blue', 10],
    'David': ['purple', 7],
    'Deborah': ['red', 6],
    'Donald': ['gray', 7],
}

colors = Counter()
numbers = Counter()

for c, n in my_dict.values():
    colors[c] += 1
    numbers[n] += 1

print(colors)
# Counter({'blue': 3, 'purple': 2, 'green': 2, 'orange': 1, 'pink': 1, 'red': 1, 'gray': 1})
print(numbers)
# Counter({7: 3, 1: 2, 2: 1, 5: 1, 6: 1, 8: 1, 9: 1, 10: 1})

答案 1 :(得分:0)

使用简单的迭代。

my_dict= {
'Barbara': ['blue', 5],
'Betty': ['purple', 8],
'Brian': ['orange', 7],
'Carol': ['green', 1],
'Charles': ['green', 9],
'Christopher': ['pink', 2],
'Cynthia': ['blue', 1],
'Daniel': ['blue', 10],
'David': ['purple', 7],
'Deborah': ['red', 6],
'Donald': ['gray', 7],
}

c = {}
n = {}
for k,v in my_dict.items():
    if v[0] not in c:
        c[v[0]] = v[1]
    else:
        c[v[0]] += v[1]

    if v[1] not in n:
        n[v[1]] = 1
    else:
        n[v[1]] += 1

print(c)
print(n)

<强>输出:

{'blue': 16, 'gray': 7, 'purple': 15, 'pink': 2, 'green': 10, 'orange': 7, 'red': 6}
{1: 2, 2: 1, 5: 1, 6: 1, 7: 3, 8: 1, 9: 1, 10: 1}