0

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.

  • 2
    Edit 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 Answers2

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.

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.

Karnage
  • 477
  • 2
  • 9