Home > Net >  How to count frequency of multiple items in a list and print relative frequencies
How to count frequency of multiple items in a list and print relative frequencies

Time:10-01

Given two lists, I need to count the frequency of the items in one list as they are found the other list; and place the relative frequencies of each item inside frequencyList (where the frequency of searchFor[0] is stored in frequencyList[0])
I am unable to import anything

    textList=['a','b','a','c',...]    
    searchFor=['a','b']   
    frequencyList=[2,1]

CodePudding user response:

Try:

[textList.count(i) for i in searchFor]

Or?

list(map(textList.count, searchFor))

CodePudding user response:

The other answer is quite compact and very pythonic but this is an alternate solution that is slightly more efficient as it only requires one pass over the input list.

textList=['a','b','a','c']
output_dict = {}

for i in textList:
    try:
        output_dict[i] = d[i]   1
    except:
        output_dict[i] = 1

print(output_dict['a'])
  • Related