我有两个列表,其中包含点的 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/