Search code examples
pythonlistcounter

Assign value from Counter to a list


Suppose I have the following lists:

l1 = ['Hello', 'world', 'world']
l2 = ['Hello', 'world', 'world', 'apple']

for l1 I count the distinct element as:

Counter(l1)

that gives:

Counter({'Hello': 1, 'world': 2})

now I would want to go through l2 and assign the values above to it such that I get:

[1,2,2,0]

as you can see for apple we assigned 0 as there is no value for it in the counter. I wonder how can I do this?


Solution

  • You can use a list comprehension like so.

    from collections import Counter
    
    l1 = ['Hello', 'world', 'world']
    l2 = ['Hello', 'world', 'world', 'apple']
    
    c1 = Counter(l1)
    
    res = [c1[i] for i in l2]
    print(res)
    

    Output

    [1, 2, 2, 0]
    

    Old Solution (before the comment by user2357112 supports Monica)

    res = [c1.get(i, 0) for i in l2]