简体   繁体   中英

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM