- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个列表 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 语句!
关于python - 从一堆列表中挑选最常见的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36165246/
我即将将主干中的某些修订合并到发布分支中。我用 mergeinfo 检查了有多少修订符合合并条件,结果是 42。尽管检查每个修订日志并决定是否应该合并它绝对是可能的并且不太难。然后,我将使用 Tort
我有 5 个文件夹,每个文件夹包含大小为 10KB、500KB、1MB、5MB 和 30MB 的“n”个文件。现在我需要从这些文件夹中选择正好 15000 个文件并将它们放入一个新文件夹中,这样我就可
嗨,我已经成功解析了一个以公里为单位的距离的 XML 文件。但结果我得到了源距离列表,但列表中的最后一个元素包含列表中所有其他元素的总和。如何获取列表中的最后元素 一些源代码: for(int s=0
我正在尝试修剪它,它存储在一个名为 $line 的变量中。 [2012-06-18 10:37:09,026 (there is a lot of text after this, i just cu
我正在使用 Python Selenium 绑定(bind)并测试网络服务器。我试图断言文本“回归”和“回归测试”的存在。有谁知道如何做吗?这是我在检查我感兴趣的元素时看到的内容: Regressi
我是一名优秀的程序员,十分优秀!