Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of times an item occurs in a list base on another list

suppose I have two lists as follows:

list1 = ["a","b","a","a","b","a","b","a","b","b","b"]
list2 = ["pos","neg","pos","neu","neg","pos","pos","pos","neg","neu","pos"]

I want to count the number of times "pos","neg" and "neu" has occurred for each item in list1.

So the number of times "pos","neg" and "neu" occurs with "a", and for "b". For example, the first element in list1, "a" has a "pos" value because list2[0] is for "pos".

What is the best approach for this? I feel there is a much better solution out there in comparison to what I have done at the moment. I can see that if more unique items exist in list1 my approach will not be feasible.

list1 = ["a","b","a","a","b","a","b","a","b","b","b"]
list2 = ["pos","neg","pos","neu","neg","pos","pos","pos","neg","neu","pos"]

a_pos = 0
a_neg = 0
a_neu = 0
b_pos = 0
b_neg = 0
b_neu = 0

for i in range(len(list1)):
    if list1[i] == "a":
        if list2[i] == "pos":
            a_pos +=1
        elif list2[i] == "neg":
            a_neg +=1
        else:
            a_neu +=1
    if list1[i] == "b":
        if list2[i] == "pos":
            b_pos +=1
        elif list2[i] == "neg":
            b_neg +=1
        else:
            b_neu +=1       

print(a_pos,a_neg,a_neu)
print(b_pos,b_neg,b_neu)
like image 824
Mark Avatar asked Dec 08 '22 12:12

Mark


1 Answers

You could use Counter with zip:

from collections import Counter
Counter(zip(list1, list2))

Counter({('a', 'pos'): 4,
         ('b', 'neg'): 3,
         ('a', 'neu'): 1,
         ('b', 'pos'): 2,
         ('b', 'neu'): 1})

Where zip is creating an iterable with the elements from both lists interleaved:

[('a', 'pos'), ('b', 'neg'), ('a', 'pos'),...

So the above works because zip is returning tuples, which are hashable, a necessary condition for Counter to work as its elements are stored as a dictionary

like image 198
yatu Avatar answered Dec 28 '22 05:12

yatu