T
T
Timebird2017-10-09 01:59:22
Python
Timebird, 2017-10-09 01:59:22

How, having found the values ​​in one list, count the number of the same values ​​in the second?

Example:
Let's say there is a list: lst1 = [a, b, c]. And the second list: lst2 = [d, a d, e, a , f, a , d, b, b, c, a , b, k, e, a , c, c, b].
It is necessary to find the number of the same a , b , c in lst2 for each of the values ​​of lst1, so that the output is as follows:
a: 5
b: 4
c: 3
How is this implemented using a dictionary? Maybe there is some elegant solution to not block the counters for each of the values ​​of lst1?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Moseychuk, 2017-10-09
@Timebird

from collections import Counter

lst1 = ["a", "b", "c"]
lst2 = ["d", "a" "d", "e", "a", "f", "a", "d", "b", "b", "c", "a", "b", "k", "e", "a", "c", "c", "b"]

counter = Counter(lst2)
for key in lst1:
    print(f'{key}: {counter[key]}')

H
Hrabry, 2017-10-09
@Hrabry

Use the dictionary generator - you will get the most elegant solution (and most importantly, the fastest one):
print({key: lst2.count(key) for key in lst1})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question