Python 在列表中查找频率的代码。第二个代码——带有count函数的代码——工作得很好,但是使用循环的第一个方法不';我不工作,为什么?
此代码没有给出正确的输出,如下所示: {('m',2),('m',1),('b',1),('p',3),('b',0),('p',2),('b',3),('m',3),('b',2),('p',1)} 此代码给出正确的输出,如下所示: {('m',2),('p',2),('b',3)}Python 在列表中查找频率的代码。第二个代码——带有count函数的代码——工作得很好,但是使用循环的第一个方法不';我不工作,为什么?,python,list,set,counting,ranged-loops,Python,List,Set,Counting,Ranged Loops,此代码没有给出正确的输出,如下所示: {('m',2),('m',1),('b',1),('p',3),('b',0),('p',2),('b',3),('m',3),('b',2),('p',1)} 此代码给出正确的输出,如下所示: {('m',2),('p',2),('b',3)} 对此作业使用计数器 names = ["b", "b", "b", "m", "p", "p"
对此作业使用
计数器
names = ["b", "b", "b", "m", "p", "p", "m"]
#made the set so that I can record the frequencies of each word only once,
#since it doesn't allow repetation
check = set()
for i in names:
#tuple, because it's hashable
my_tup = (i, names.count(i))
check.add(my_tup)
print(check)
names = ["b", "b", "b", "m", "p", "p", "m"]
#made the set so that I can record the frequencies of each word only once,
#since it doesn't allow repetation
check = set()
for i in names:
#tuple, because it's hashable
my_tup = (i, names.count(i))
check.add(my_tup)
print(check)
from collections import Counter
print(Counter(["b", "b", "b", "m", "p", "p", "m"]))