Python – 多个列表中的元素频率计数
有时在使用Python列表时,我们可能会遇到需要提取列表中元素频率的问题。但是,如果我们处理的列表超过 1 个,则可以添加工作。让我们讨论可以执行此任务的某些方式。
方法 #1:使用字典理解 + set() + count()
这是可以执行此任务的方式之一。在此,我们使用 count() 和 set() 执行计数任务,并使用字典理解完成逻辑扩展。
# Python3 code to demonstrate
# Elements frequency count in multiple lists
# using set() + count() + dictionary comprehension
# Initializing lists
test_list1 = [1, 3, 2, 4, 5, 1, 2]
test_list2 = [4, 1, 4, 3, 4, 2, 4]
test_list3 = [1, 4, 5, 3, 4, 5, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# Elements frequency count in multiple lists
# using set() + count() + dictionary comprehension
res = {idx : [test_list1.count(idx), test_list2.count(idx), test_list3.count(idx)]
for idx in set(test_list1 + test_list2 + test_list3)}
# printing result
print ("The frequency of each element is : " + str(res))
The original list 1 is : [1, 3, 2, 4, 5, 1, 2]
The original list 2 is : [4, 1, 4, 3, 4, 2, 4]
The original list 3 is : [1, 4, 5, 3, 4, 5, 4]
The frequency of each element is : {1: [2, 1, 1], 2: [2, 1, 0], 3: [1, 1, 1], 4: [1, 4, 3], 5: [1, 0, 2]}
方法 #2:使用Counter() + map()
+ 字典理解
上述功能的组合可以用来解决这个问题。在此,查找频率的任务是使用 Counter() 和 map() 完成的。
# Python3 code to demonstrate
# Elements frequency count in multiple lists
# using map() + Counter() + dictionary comprehension
from collections import Counter
# Initializing lists
test_list1 = [1, 3, 2, 4, 5, 1, 2]
test_list2 = [4, 1, 4, 3, 4, 2, 4]
test_list3 = [1, 4, 5, 3, 4, 5, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# Elements frequency count in multiple lists
# using map() + Counter() + dictionary comprehension
freq = list(map(Counter, (test_list1, test_list2, test_list3)))
res = {ele: [cnt[ele] for cnt in freq] for ele in {ele for cnt in freq for ele in cnt}}
# printing result
print ("The frequency of each element is : " + str(res))
The original list 1 is : [1, 3, 2, 4, 5, 1, 2]
The original list 2 is : [4, 1, 4, 3, 4, 2, 4]
The original list 3 is : [1, 4, 5, 3, 4, 5, 4]
The frequency of each element is : {1: [2, 1, 1], 2: [2, 1, 0], 3: [1, 1, 1], 4: [1, 4, 3], 5: [1, 0, 2]}