Skip to main content
 首页 » 编程设计

python之从一堆列表中挑选最常见的元素

2025年05月04日10zengkefu

我有一个列表 l 的列表 [l1, ..., ln] 等长

我想比较 len(l1) 中所有 k 的 l1[k], l2[k], ..., ln[k] ) 并通过选择出现频率最高的元素制作另一个列表 l0。

所以,如果 l1 = [1, 2, 3],l2 = [1, 4, 4] 和 l3 = [0, 2, 4],然后 l = [1, 2, 4]。如果有平局,我将查看构成平局的列表并选择列表中优先级更高的列表。优先级是先验的,每个列表都有一个优先级。 前任。如果您在列表 l1 和 l3 中有值 1,在列表 l2 和 l4 中有值 2,以及 3在 l5 中,列表根据优先级排序,比如 l5>l2>l3>l1>l4,那么我会选择 2,因为 2 在 l2 中 包含出现次数最多的元素,其优先级高于 l1 和 l3。

如何在 python 中执行此操作而不创建包含大量 if/else 条件的 for 循环?

请您参考如下方法:

您可以使用集合库中的计数器模块。使用 map 函数将减少列表循环。如果没有最频繁出现的值,你将需要一个 if/else 语句:

import collections 
 
list0 = [] 
list_length = len(your_lists[0]) 
for k in list_length: 
    k_vals = map(lambda x: x[k], your_lists) #collect all values at k pos 
    counts = collections.Counter(k_vals).most_common() #tuples (val,ct) sorted by count 
    if counts[0][1] > counts[1][1]: #is there a most common value 
        list0.append(counts[0][0]) #takes the value with highest count 
    else: 
        list0.append(k_vals[0]) #takes element from first list 

list0 是您正在寻找的答案。我只是讨厌使用 l 因为它很容易与数字 1

混淆

编辑(根据评论):
合并您的评论,而不是 if/else 语句,使用 while 循环:

i = list_length 
while counts[0][1] == counts[1][1]: 
    counts = collections.Counter(k_vals[:i]).most_common() #ignore the lowest priority element 
    i -= 1 #go back farther if there's still a tie 
list0.append(counts[0][0]) #takes the value with highest count once there's no tie 

所以现在整个事情是:

import collections 
 
list0 = [] 
list_length = len(your_lists[0]) 
for k in list_length: 
    k_vals = map(lambda x: x[k], your_lists) #collect all values at k pos 
    counts = collections.Counter(k_vals).most_common() #tuples (val,ct) sorted by count 
    i = list_length 
    while counts[0][1] == counts[1][1]: #in case of a tie 
        counts = collections.Counter(k_vals[:i]).most_common() #ignore the lowest priority element 
        i -= 1 #go back farther if there's still a tie 
    list0.append(counts[0][0]) #takes the value with highest count 

你又加入了一个小循环,但好的一面是根本没有 if/else 语句!