Python:在对应的两个列表中找到最常见的元素

标签 python list

我有两个列表,其中包含点的 x 和 y 坐标,其中每个对应元素代表一个点。

举个例子,X_List = [1, 3, 1, 4], Y_List = [6, 7, 6, 1] 那么点就是(1,6) (3,7) (1,6) (4 ,1).因此,最常见的点是 (1,6)。

这是我的代码:

Points=[]
for x,y in zip(X_List, Y_List):
Points.append([x,y])
MostCommonPoint = max(set(Points), key=Points.count)

但是,这不会像 Points 那样在不可散列类型的列表中工作。

最佳答案

首先,zip 返回元组列表(或 Python 3 中的元组迭代器)。这意味着您可以在 Python 3 上使用 zip(X_List, Y_List) 而不是 Points (或 list(zip(X_List, Y_List)) ), 你的代码就可以工作了。但是,这需要二次方时间。

更快的方法是使用 collections.Counter ,这是一个为计数而设计的字典子类:

import collections

# Produce a Counter mapping each point to how many times it appears.
counts = collections.Counter(zip(X_List, Y_List))

# Find the point with the highest count.
MostCommonPoint = max(counts, key=counts.get)

关于Python:在对应的两个列表中找到最常见的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24790659/

相关文章:

python - PyOpenGL 将变量传递给顶点着色器

list - 在 Flutter/Dart 中映射多个列表?

列表中的 Python 函数

java - 访问对象列表中对象中的字段

python - 从计数器常用键列表中摘录

c# - 如果一个字符串存在于大量对象列表中,比较最快的(性能)方法是什么?

python - Appengine NDB 事务类方法装饰器顺序

python - 为什么每个 Gauss-Seidel 迭代都会执行两次组件? (OpenMDAO 2.4.0)

python - 在 Python (PyQt) 中创建二维码

python - 如何处理导入错误?