gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:21 25 4
gpt4 key购买 nike

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

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

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

如何在 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 语句!

关于python - 从一堆列表中挑选最常见的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36165246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com