繁体   English   中英

Python - 计算列表中字符串的频率

[英]Python - Counting frequency of strings in a list

我想知道如何计算列表中字符串的频率并使用它们。

example list: fruits = (['apple', 'banana', 'banana', 'apple', 'mango'])
def fruitcounter():
    from collections import Counter
    a = Counter(fruits)
    return(a)
Counter({'apple': 2, 'banana': 2, 'mango': 1})

水果列表是随机的。 有什么方法可以使用这些数字并分配它们,以便我可以进行其他计算,例如列表中苹果的百分比?

使用字典理解将所有计数除以列表的长度。

a = Counter(fruits)
percents = {fruit: count/len(fruits)*100 for fruit, count in a.items()}

结果:

{'apple': 40, 'banana': 40, 'mango': 20}

您可以以太用户len(fruits)或总结计数器值以获得总水果数量:

from collections import Counter

fruits = (['apple', 'banana', 'banana', 'apple'])
counts = Counter(fruits)
totals = sum(counts.values())

bananaPercent = 100/totals*counts['banana']
print('You got %s percent bananas!' % bananaPercent)

输出:

You got 50 percent bananas!

编辑,以防你不知道水果:

from collections import Counter

fruits = (['apple', 'banana', 'banana', 'apple'])
counts = Counter(fruits)
totals = sum(counts.values())

for k in counts.keys():
    kPercent = 100/totals*counts[k]
    print('%ss make %s percent!' % (k, kPercent))

输出:

apples make 50 percent!
bananas make 50 percent!

要计算列表中苹果的百分比,您可以访问苹果的频率并除以水果的总量,如下所示:

from collections import Counter
fruits = ['apple', 'banana', 'banana', 'apple', 'mango']

c = Counter({'apple': 2, 'banana': 2, 'mango': 1})
apple_percentage = 100 * c['apple']/len(fruits)
print(f'{apple_percentage}%')

输出:

40.0%

尝试在不使用计数器库的情况下执行此操作

fruit=['apple', 'banana', 'banana', 'apple', 'mango']
unique_words = set(fruit) 
c=[]  
countvalue={}
allpercent={}
for key in unique_words: 
        c= fruit.count(key)     #count no of fruits
        countvalue[key]=c   
        percent=c/len(fruit)*100  #calculate percent
        allpercent[key] = percent
        print('percent of ',key,' is ' , percent)
print('\ncounts no of fruits in dictionary \n')  
print(countvalue)

print('\npercentage value in dictionary \n')
print(allpercent)
#output
##percent of  mango  is  20.0
#percent of  banana  is  40.0
#percent of  apple  is  40.0

#counts no of fruits in dictionary 

#{'mango': 1, 'banana': 2, 'apple': 2}

#percentage value in dictionary 

#{'mango': 20.0, 'banana': 40.0, 'apple': 40.0}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM