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

2024-06-11 21:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但是,这将不能作为不可损坏类型的列表中的工作。


Tags: key代码in元素列表for代表zip
3条回答

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

一种更快的方法是使用^{},这是一个dict子类,用于计数:

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)

使用计数器:

>>> from collections import Counter

它很简单:

^{pr2}$

一步一步

构建点列表:

>>> x_lst = [1, 3, 1, 4]
>>> y_lst = [6, 7, 6, 1]
>>> pnts = zip(x_lst, y_lst)
>>> pnts
[(1, 6), (3, 7), (1, 6), (4, 1)]

创建一个counter,它可以计算所有项目:

>>> counter = Counter(pnts)
>>> counter
Counter({(1, 6): 2, (3, 7): 1, (4, 1): 1})

获取(一)最常见项目的列表:

>>> counter.most_common(1)
[((1, 6), 2)]

获取项目本身:

>>> counter.most_common(1)[0][0]
(1, 6)

@jan vlcinsky是对的。另一个似乎有效的简单方法如下。不过,我还没有比较表演。在

REPL: https://repl.it/C9jQ/0

Gist: https://gist.github.com/ablaze8/845107aa8045507057c1e71b81f228f4

Blog Post: https://WildClick.WordPress.com/

import itertools

a = [7, 3]
b = [3, 1, 2]
c = [4, 3, 5]


def allEqual(t):
    same = True

    if len(t) == 1:
        return True

    if len(t) == 0:
        return False

    for i in range(1, len(t)):
        if t[i] != t[i - 1]:
            same = False
            i = len(t) - 1
        else:
            same = same and True

    return same


combo = list(itertools.product(a, b, c))
# print list(itertools.permutations(a,2))
# print combo

# combo = [x for x in combo if x[0]==x[1]==x[2]]
# print combo

combo = [x for x in combo if allEqual(x)]
print combo

相关问题 更多 >