Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列表中查找频率的代码。第二个代码——带有count函数的代码——工作得很好,但是使用循环的第一个方法不';我不工作,为什么?_Python_List_Set_Counting_Ranged Loops - Fatal编程技术网

Python 在列表中查找频率的代码。第二个代码——带有count函数的代码——工作得很好,但是使用循环的第一个方法不';我不工作,为什么?

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"

此代码没有给出正确的输出,如下所示: {('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", "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"]))