如何计算python中list的所有元素的出现?

时间:2019-11-21 19:39:07

标签: python-3.x list

1 个答案:

答案 0 :(得分:2)

您可以使用count()方法计算特殊元素的出现次数:

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']
letters = ['a', 'b', 'c', 'd', 'f']

print(list(map(lambda letter: {letter: grades.count(letter)}, letters)))

输出:

[{'a': 4}, {'b': 4}, {'c': 2}, {'d': 2}, {'f': 1}]

如果您不想使用letters来执行此操作。您可以这样做:

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']

print(list(map(lambda letter: {letter: grades.count(letter)}, set(grades))))

输出:

[{'f': 1}, {'b': 4}, {'c': 2}, {'d': 2}, {'a': 4}]

对于您的预期输出:

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']

occurrence = map(lambda letter: (letter, grades.count(letter)), set(grades))

for item in occurrence:
    print(f"{item[0]}={item[1]}")

输出:

c=2
b=4
d=2
f=1
a=4

更新

您可以使用defaultdict()计算每个元素的出现次数:

from collections import defaultdict

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']
occurrence = defaultdict(lambda: 0)

for character in grades:
    occurrence[character] += 1

for key, value in occurrence.items():
    print(f"{key}={value}")

输出:

b=4
f=1
c=2
a=4
d=2