繁体   English   中英

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

[英]Python: find most common element in corresponding two lists

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

但是,这不适用于作为不可用类型的列表中的

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

更快的方法是使用collections.Counter ,它是一个用于计算事物的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

它很简单:

>>> Counter(zip(x_lst, y_lst)).most_common(1)[0][0]
(1, 6)

一步步

建立点列表:

>>> 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

要点: https//gist.github.com/ablaze8/845107aa8045507057c1e71b81f228f4

博客文章: 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM