2014-07-16 137 views
2

我有兩個列表,其中每個對應元素表示一個點,其中包含點的x座標和y座標。只是一個例子,X_List = [1,3,1,4],Y_List = [6,7,6,1],那麼點是(1,6)(3,7)(1,6)( 4,1)。因此,最常見的一點是(1,6)。Python:在相應的兩個列表中找到最常見的元素

這裏是我的代碼:

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

但是,這是行不通的工作作爲在列表是unhashable類型。

回答

4

首先,zip返回元組列表(或Python 3中元組的迭代器)。這意味着您可以使用zip(X_List, Y_List)而不是Points(或Python 3上的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) 
+1

您還可以使用counts.most_common(1)獲得(含列表)的最常見的一點。這簡單得多一點,並且節省了對集合的另一次迭代。 (在這種情況下可能不會節省很多,但總的來說很好。) – Weeble

+0

@Weeble:'most_common(1)'最後調用'max'。用'[0] [0]'提取列表的一個元素,然後提取元素計數元組的第一部分,我認爲即使在代碼簡單性方面也是如此。 – user2357112

+0

啊,夠公平的。我錯誤地認爲Counter內容是按順序維護的,但它看起來像most_common(n)使用heapq.nlargest遍歷集合。同意,一旦你考慮解構結果就會否定簡單的好處。 – Weeble

3

使用計數器:

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

@ 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 
相關問題