2009-09-07 80 views

回答

289

不是最有效的,但目前爲止最明顯的方式做到這一點是:

>>> [i for i, j in zip(a, b) if i == j] 
[5] 

>>> a = [1, 2, 3, 4, 5] 
>>> b = [9, 8, 7, 6, 5] 
>>> set(a) & set(b) 
{5} 

如果順序顯著你可以用列表理解這樣做(只適用於大小相同的列表,這些順序意義暗示着)。

+5

一個值得注意的問題,列表理解是*不*一定是更快的選擇。對於更大的集合(性能最有可能成立),按比較('&')或'set(a).intersection(b)'將比列表理解更快或更快。 – Joshmaker 2012-06-03 17:00:22

+5

另一個值得注意的事項是:列表理解找到兩個同樣位置出現的值(這是SilentGhost意思是「順序很重要」)。設定的路口解決方案也會在不同的位置找到匹配。這些是對兩個完全不同的問題的回答......(op的問題與它所要求的模糊不清) – drevicko 2013-11-24 22:58:01

+0

如果你的列表是列表列表,即a = [[0,0],[1, 0]]和b = [[2,3],[0,0]] – Schneems 2017-03-12 21:18:24

11

做到這一點的最簡單的方法是使用sets

>>> a = [1, 2, 3, 4, 5] 
>>> b = [9, 8, 7, 6, 5] 
>>> set(a) & set(b) 
set([5]) 
260

使用set.intersection(),它的快速性和可讀性。

>>> set(a).intersection(b) 
set([5]) 
+22

此答案具有良好的算法性能,因爲只有其中一個列表(應該是首選的較短)被轉換爲快速查找的集合,而另一個列表則遍歷查找集合中的項目。 – u0b34a0f6ae 2009-09-07 12:08:11

+3

'bool(set(a).intersection(b))''True'或'False' – Akshay 2017-10-20 03:20:16

+0

由於人們可能需要['difference'](https://docs.python。 org/3/library/stdtypes.html#frozenset.difference)或['union'](https://docs.python.org/3/library/stdtypes.html#frozenset.union)。 – 2017-11-01 02:31:15

5

你要重複?如果沒有,也許你應該使用組,而不是:


>>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5])) 
set([5]) 
+0

如果您確實需要列表,請將相交([1,2,3,4,5],[9,8,..., 7,6,5]) [5] – 2009-09-07 11:16:59

+0

根據文檔 - * ...排除像Set('abc')&'cbs'這樣容易出錯的構造,使其更易讀Set('abc')。交叉點('cbs')。* - http://docs.python.org/library/sets.html – 2012-05-31 13:40:47

3

您可以使用

def returnMatches(a,b): 
     return list(set(a) & set(b)) 
9
>>> s = ['a','b','c'] 
>>> f = ['a','b','d','c'] 
>>> ss= set(s) 
>>> fs =set(f) 
>>> print ss.intersection(fs) 
    **set(['a', 'c', 'b'])** 
>>> print ss.union(fs)   
    **set(['a', 'c', 'b', 'd'])** 
>>> print ss.union(fs) - ss.intersection(fs) 
    **set(['d'])** 
+0

接受的答案對包含字符串的列表無效。這個呢。 – Antony 2018-01-25 16:18:05

8

而且你可以通過在一個新列表中保存常用元素來嘗試這一點。

new_list = [] 
for element in a: 
    if element in b: 
     new_list.append(element) 
64

顯示盧茨的解決方案快速的性能測試是最好的:

import time 

def speed_test(func): 
    def wrapper(*args, **kwargs): 
     t1 = time.time() 
     for x in xrange(5000): 
      results = func(*args, **kwargs) 
     t2 = time.time() 
     print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0) 
     return results 
    return wrapper 

@speed_test 
def compare_bitwise(x, y): 
    set_x = frozenset(x) 
    set_y = frozenset(y) 
    return set_x & set_y 

@speed_test 
def compare_listcomp(x, y): 
    return [i for i, j in zip(x, y) if i == j] 

@speed_test 
def compare_intersect(x, y): 
    return frozenset(x).intersection(y) 

# Comparing short lists 
a = [1, 2, 3, 4, 5] 
b = [9, 8, 7, 6, 5] 
compare_bitwise(a, b) 
compare_listcomp(a, b) 
compare_intersect(a, b) 

# Comparing longer lists 
import random 
a = random.sample(xrange(100000), 10000) 
b = random.sample(xrange(100000), 10000) 
compare_bitwise(a, b) 
compare_listcomp(a, b) 
compare_intersect(a, b) 

這是我的機器上的結果:

# Short list: 
compare_bitwise took 10.145 ms 
compare_listcomp took 11.157 ms 
compare_intersect took 7.461 ms 

# Long list: 
compare_bitwise took 11203.709 ms 
compare_listcomp took 17361.736 ms 
compare_intersect took 6833.768 ms 

顯然,任何人爲的性能測試應採取一粒鹽,但由於set().intersection()的答案是至少與其他解決方案一樣快,也是最readab樂,它應該是這個常見問題的標準解決方案。

1

您可以使用:

a = [1, 3, 4, 5, 9, 6, 7, 8] 
b = [1, 7, 0, 9] 
same_values = set(a) & set(b) 
print same_values 

輸出:

set([1, 7, 9]) 
+3

這與6年前的接受答案有何不同? – tom 2016-01-06 11:12:28

+1

那麼,我寫了輸出的完整細節和良好的初學者python – 2016-01-06 13:10:58

1

另一個更實用一點的方法來檢查清單1(LST1)和表2(LST2)名單平等,其中的對象具有深度一個和它保持的順序是:

all(i == j for i, j in zip(lst1, lst2)) 
3

也可以使用itertools.product。

>>> common_elements=[] 
>>> for i in list(itertools.product(a,b)): 
... if i[0] == i[1]: 
...  common_elements.append(i[0]) 
0

如果你想有一個布爾值:

>>> a = [1, 2, 3, 4, 5] 
>>> b = [9, 8, 7, 6, 5] 
>>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b) 
False 
>>> a = [3,1,2] 
>>> b = [1,2,3] 
>>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b) 
True 
0

使用__and__屬性方法也適用。

>>> a = [1, 2, 3, 4, 5] 
>>> b = [9, 8, 7, 6, 5] 
>>> set(a).__and__(set(b)) 
set([5]) 

或者乾脆

>>> set([1, 2, 3, 4, 5]).__and__(set([9, 8, 7, 6, 5])) 
set([5]) 
>>>  
1
a = [1, 2, 3, 4, 5] 
b = [9, 8, 7, 6, 5] 

lista =set(a) 
listb =set(b) 
print listb.intersection(lista) 
returnMatches = set(['5']) #output 

print " ".join(str(return) for return in returnMatches) # remove the set() 

5  #final output 
+0

雖然這段代碼可能回答這個問題,提供額外的上下文關於如何和/或爲什麼它解決問題將提高答案的長期價值。 – 2017-07-20 00:45:57

相關問題