I have a list in python: [adam,josh,drake]
I want to output the percentage of the times that a word is used out of all of the words(eg. adam-33%, josh 33% etc.). So that if I add a word to the list, the percentage will change accordingly.
Asked
Active
Viewed 2,423 times
0
![](../../users/profiles/6707425.webp)
adaminspaceship
- 65
- 1
- 9
-
2Edit the question and post your code, my suggestion would be to run a loop or two through the list and get the frequency of each name then divide that by the total number of names in the list for each name – Nov 01 '16 at 05:16
2 Answers
4
You can use collections.Counter
to count how often each word occurs.
Then you can iterate through the resulting object and divide each count by the length of the original list to get a decimal percentage from 0.0 to 1.0, which can be multiplied by 100 to give a percentage between 0 and 100 to be printed out.
![](../../users/profiles/148870.webp)
Amber
- 446,318
- 77
- 595
- 531
1
You should look at the collections module, in particular https://docs.python.org/3/library/collections.html#collections.Counter
from collections import Counter
names = ['adam','josh','drake']
count = Counter(names).items()
percentages = {x: int(float(y) / len(names) * 100) for x, y in count}
for name, pct in percentages.iteritems():
print '%s - %s%s' % (name, pct, '%')
The items method on the Counter produces a list of tuples of the name and the number of times that name appears in the original list.
![](../../users/profiles/6924242.webp)
Karnage
- 477
- 2
- 9
-
-
for name, pct in percentages.iteritems(): print '%s: %s' % (name, pct) – Karnage Nov 01 '16 at 05:28
-
That would be one name and count per line, but there are lots of ways to print it out. What sort of output were you wanting to get? – Karnage Nov 01 '16 at 05:30
-
-
-
-
Maybe if count was a dict, but it has been transformed into a list of tuples. Besides, the numbers are exactly the same and len both looks better on the screen and takes fewer resources. – Karnage Nov 01 '16 at 06:43