我必须将所有元素以及它们的数量分别写出。 It's the program i have made. It is counting correctly but not giving required output
The output is like this I want output to be like this. All digits showing individual complete count
答案 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