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