2010-05-19 78 views
45
def common_elements(list1, list2): 
    """ 
    Return a list containing the elements which are in both list1 and list2 

    >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) 
    [3, 5] 
    >>> common_elements(['this','this','n','that'],['this','not','that','that']) 
    ['this', 'that'] 
    """ 
    for element in list1: 
     if element in list2: 
      return list(element) 

到目前爲止,但似乎無法使其工作!由於2個列表之間的通用元素比較

回答

97
>>> list1 = [1,2,3,4,5,6] 
>>> list2 = [3, 5, 7, 9] 
>>> list(set(list1).intersection(list2)) 
[3, 5] 
+0

+1而我個人倒用frozenset,因爲它是不可變的,因此可以作爲字典的鍵等 – zebrabox 2010-05-19 11:04:53

+6

這將返回/獨特/共同的元素,但不是可能存在的任何重複的元素。 – Dologan 2014-03-20 18:52:18

+0

@SilentGhost。如何從兩個列表中獲取匹配元素的數量。在這種情況下,它是2。 – Poka 2017-12-09 11:53:38

17

使用一套交叉口,設置(列表1)&集(列表2)

>>> def common_elements(list1, list2): 
...  return list(set(list1) & set(list2)) 
... 
>>> 
>>> common_elements([1,2,3,4,5,6], [3,5,7,9]) 
[3, 5] 
>>> 
>>> common_elements(['this','this','n','that'],['this','not','that','that']) 
['this', 'that'] 
>>> 
>>> 

注意,結果列表可能是不同的順序與原來的名單。

+0

感謝您的幫助。瞭解我出錯的地方以及下次要做什麼。 :) – Daniel 2010-05-19 12:29:48

+0

這太棒了,丹尼爾:-) – YOU 2010-05-19 12:47:13

+1

偉大的解決方案。還有一種方法可以通過這個來保存訂單嗎? – tarrasch 2012-08-30 15:47:04

22

S.MarkSilentGhost建議的解決方案通常會告訴您應該如何以Pythonic方式完成,但我認爲您也可以從知道您的解決方案不起作用的原因中受益。問題是,只要你找到兩個列表中的第一個公共元素,就只返回那個單一元素。

def common_elements(list1, list2): 
    result = [] 
    for element in list1: 
     if element in list2: 
      result.append(element) 
    return result 

更短的版本使用列表理解:您的解決方案可以通過創建一個result列表,該列表中收集的共同要素是固定

def common_elements(list1, list2): 
    return [element for element in list1 if element in list2] 

然而,正如我所說,這是一個這樣做非常低效 - Python的內置集合類型在內部用C實現時效率更高。

+0

對兩個提議都很好 – dlewin 2015-09-21 12:41:20

+0

注意:上述方法只適用於相同大小的列表。如果您正在處理大小不一的列表,那麼您需要在調用函數之前根據len()評估訂單: list1 = [2,2,2],list2 [2,3] - > [2,2,2] list1 = [2,3],list2 [2,2,2] - > [2] – redthumb 2016-09-30 11:56:41

8

以前的答案都可以找到唯一的共同元素,但是無法解釋列表中的重複項。如果你想共同要素出現在相同數量,因爲它們是在共同發現的列表,可以使用下面的一行代碼:

l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)] 

,如果你希望的任何元素的or True部分只需要評估爲False

+0

真棒解決方案,似乎是最徹底的,如果有點簡潔 – Hendeca 2017-03-08 21:25:58

+0

這應該是答案應該已經被選中了!我假設它也適用於不平等的名單。此外,大多數解決方案使用不穩定的「集合」(又稱訂單丟失)。 – lifebalance 2017-06-15 14:14:41

1

1)方法1 節省list1的是字典,然後迭代在list2中每個ELEM

def findarrayhash(a,b): h1={k:1 for k in a} for val in b: if val in h1: print("common found",val) del h1[val] else: print("different found",val) for key in h1.iterkeys(): print ("different found",key)尋找共同和不同的元素:

2)方法2 使用設置

def findarrayset(a,b): common = set(a)&set(b) diff=set(a)^set(b) print list(common) print list(diff)

0

這裏的我想出了一個相當暴力的方法。這當然不是最有效的,但它是一些東西。

我在這裏找到的一些解決方案存在的問題是,它不會給出重複的元素,或者當輸入順序很重要時它不會給出正確數量的元素。

#finds common elements 
def common(list1, list2): 
    result = [] 
    intersect = list(set(list1).intersection(list2)) 

    #using the intersection, find the min 
    count1 = 0 
    count2 = 0 
    for i in intersect: 
     for j in list1: 
      if i == j: 
       count1 += 1 
     for k in list2: 
      if i == k: 
       count2 += 1 
     minCount = min(count2,count1) 
     count1 = 0 
     count2 = 0 

     #append common factor that many times 
     for j in range(minCount): 
      result.append(i) 

    return result 
16

您也可以使用集合並在一行中獲得共同性:從包含集合中的差異的集合中減去集合。

A = [1,2,3,4] 
B = [2,4,7,8] 
commonalities = set(A) - (set(A) - set(B))