2017-10-20 63 views
-3

我使用python来计算列表的频率而不使用使用任何集合只是我自己的python基本函数。 我的代码是:Python:计数字符串频率列表类型

my_list = ['a', 'b','a', 'a','b','b', 'a','a','c'] 

def counting(): 
#Please help 

打印出来放应该像

a: 5 
b: 3 
c: 1 

请帮忙,谢谢。

+0

这并不算作“代码”。 –

+0

函数counting()的内容是什么? – mrCarnivore

+0

@mrCarnivore哦,我只是不知道如何使它的功能。我会把它留空 –

回答

1

使用count,内置list函数。

def counting(my_list): 
     return { x:my_list.count(x) for x in my_list } 

叫它:

>>> counting(my_list) 
=> {'a': 5, 'b': 3, 'c': 1} 

#print it as per requirement 
>>> for k,v in counting(my_list).items(): 
     print(k,':',v) 

a : 5 
b : 3 
c : 1 

#driver值:

IN : my_list = ['a', 'b','a', 'a','b','b', 'a','a','c'] 
1

创建一个字典来保存结果,并检查是否存在关键增量值,否则设置的值1(第一次出现)。

my_list = ['a', 'b','a', 'a','b','b', 'a','a','c'] 

def counting(my_list): 
    counted = {} 
    for item in my_list: 
    if item in counted: 
     counted[item] += 1 
    else: 
     counted[item] = 1 

    return counted 

print(counting(my_list))