user3521035
user3521035

Reputation: 23

Find the frequency of a word in list with accordance to the first indexed item

Lets say I have a list like this

my_list = [(1, 'A'), (1, 'A'), (1, 'A'), (1, 'B'), (20, 'BB'), 
  (20, 'BB'), (100, 'CC'), (100, 'CC'), (100, 'CC')]

now i want to write a code in python 3 so that it returns the frequency of second element of item with accordance to the first item. for example I expect the output to print something like below :

1: 3 (A), 1 : 1 (B), 20: 2(BB), 100: 3(CC)

Sorry for bad English. Any help would be appreciated.

Upvotes: 0

Views: 77

Answers (2)

Harish J
Harish J

Reputation: 168

You can also use Dict to achieve this instead of importing collections. Since, the items of your list are tuples, they can be used as keys of a dictionary.

Here's how you can do this:

list = [(1, 'A'), (1, 'A'), (1, 'A'), (1, 'B'), (20, 'BB'),  (20, 'BB'), (100, 'CC'), (100, 'CC'), (100, 'CC')]

dict = {}

for item in list:
    if item in dict:
        dict[item] += 1
    else:
        dict[item] = 1
print(dict)

Upvotes: 0

Trollsors
Trollsors

Reputation: 492

Use the Counter method from the Collections module.

from collections import Counter
my_list = [(1, 'A'), (1, 'A'), (1, 'A'), (1, 'B'), (20, 'BB'), 
  (20, 'BB'), (100, 'CC'), (100, 'CC'), (100, 'CC')]
print(Counter(my_list))

Output:

Counter({(1, 'A'): 3, (100, 'CC'): 3, (20, 'BB'): 2, (1, 'B'): 1})

Upvotes: 1

Related Questions