I would like to know how to count the frequency of strings in a list and use them.
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})
The fruits list is random. Is there any way to use these numbers and assign them so I can do other calculations like the percentage of apples in the list?
Use a dictionary comprehension that divides all the counts by the length of the list.
a = Counter(fruits)
percents = {fruit: count/len(fruits)*100 for fruit, count in a.items()}
Result:
{'apple': 40, 'banana': 40, 'mango': 20}
You can ether user len(fruits)
or sum up the counter values to get the amount of total 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)
Output:
You got 50 percent bananas!
Edit, in case you dont know the fruits:
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))
Output:
apples make 50 percent!
bananas make 50 percent!
to calculate the percentage of apples in the list you could access the frequency of the apples and divide by the total amount of fruits like this:
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}%')
output:
40.0%
Try to do this without using counter library
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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.