0

I have a list that contains multiple words. It looks like this:

Food = ['apple', 'orange', 'banana', 'orange', 'strawberry', 'apple', 'orange', banana', apple']

Is there any way that I could rank the number of times each fruit is used? The code also has to allow for multiple places to make is look like this:

(apple, 1), (orange, 1), (banana, 3), (strawberry, 4).

I tried to use the ranking function but had no idea what to do after I downloaded from github and unzipped it.

I am not looking for a count of how many times each word is used but more like a ranking kind of thing. Something like 1st, 2nd, 3rd. But let's say that if two of the items have 3 occurrences while the rest have less it will look like: 1, 1, 3, 4, 5 etc.

3 Answers3

1

Use a Counter which is a subclass of a dict

In [1]: from collections import Counter

In [2]: food = ['apple', 'orange', 'banana', 'orange', 'strawberry', 'apple', 'orange', 'banana', 'apple']

In [3]: c = Counter(food)

In [4]: c
Out[4]: Counter({'apple': 3, 'banana': 2, 'orange': 3, 'strawberry': 1})

In [5]: c['orange']
Out[5]: 3
aydow
  • 3,673
  • 2
  • 23
  • 40
1

How about something like this?

Built up a dictionary of the counters, and then sort the dict by the values.

Food = ['apple', 'orange', 'banana', 'orange', 'strawberry', 'apple', 'orange', 'banana','apple']

d = {}
for fruit in Food:
    d[fruit] = d.get(fruit, 0) + 1

ranked = sorted(d.iteritems(), key=lambda x: x[1], reverse=True)

where ranked is:

[('orange', 3), ('apple', 3), ('banana', 2), ('strawberry', 1)]
LeKhan9
  • 1,300
  • 1
  • 5
  • 15
0

One solution is to add the foods to a dictionary where the value is the count. For example, here is a piece of code that goes through every food in the list and updates the count. Then, you can optionally convert it back to a list:

Food = ["apple", "orange", "banana", "orange", "strawberry", "apple", "orange", "banana", "apple"]

FoodDict = {}
for f in Food:
    if f in FoodDict:
        FoodDict[f] += 1
    else:
        FoodDict[f] = 0
print(FoodDict)
FoodCountList = [(f, FoodDict[f]) for f in FoodDict]
print(FoodCountList)

Which prints:

{'apple': 2, 'orange': 2, 'banana': 1, 'strawberry': 0}
[('apple', 2), ('orange', 2), ('banana', 1), ('strawberry', 0)]
Leo Adberg
  • 342
  • 2
  • 18