Until now, in order to check how many elements are included in the list, the list element was rotated by the for statement and the combination of the element and the number was set in the dict. However, if you use the collections.Counter class, you can process it in one line.
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
a_dict = dict()
b_dict = dict()
for item in a:
if item in a_dict:
a_dict[item] += 1
else:
a_dict[item] = 1
for item in b:
if item in b_dict:
b_dict[item] += 1
else:
b_dict[item] = 1
print(a_dict) #{1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
print(b_dict) #{1: 1, 2: 2, 3: 3, 4: 4, 6: 6}
from collections import Counter
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
a_counter = Counter(a)
b_counter = Counter(b)
print(a_counter) #Counter({5: 5, 4: 4, 3: 3, 2: 2, 1: 1})
print(b_counter) #Counter({6: 6, 4: 4, 3: 3, 2: 2, 1: 1})
from collections import Counter
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
a_counter = Counter(a)
b_counter = Counter(b)
print(a_counter + b_counter) #Counter({4: 8, 3: 6, 6: 6, 5: 5, 2: 4, 1: 2})
print(a_counter - b_counter) #Counter({5: 5})
Recommended Posts