2014-11-06 46 views
0

我有2所列出:有效的測試,如果兩個列表有相同的元素和長度

alist = ['A','B','C','D'] 
anotherList = ['A','C','B','D'] 

想編寫返回True如果兩個列表包含完全相同的元素,相同長度的函數。我對這個東西有點新,所以我得到了這個,我非常肯定它很糟糕,我試圖找到一個更有效的方法。謝謝!

def smyFunction(aList,anotherList): 
    n = 0 
    for element in aList: 
     if element in anotherList: 
      n = n+1 
    if n == len(aList): 
     return True 
    else: 
     return False 

回答

1

排序與sorted,然後列出與==對它們進行比較:

>>> alist = ['A','B','C','D'] 
>>> anotherList = ['A','C','B','D'] 
>>> def smyFunction(aList,anotherList): 
...  return sorted(aList) == sorted(anotherList) 
... 
>>> smyFunction(alist, anotherList) 
True 
>>> 

您需要首先進行排序的情況下,元素爲順序:

>>> alist = ['A','B','C','D'] 
>>> anotherList = ['D','A','C','B'] 
>>> alist == anotherList 
False 
>>> sorted(alist) == sorted(anotherList) 
True 
>>> 

其實,最好先測試一下列表的長度,然後用sorted

return len(alist) == len(anotherList) and sorted(alist) == sorted(anotherList) 

這樣一來,我們就能避免排序操作如果列表的長度不同,以開始(使用len名單上有O(1)(恆定)的複雜性,所以這是很便宜)。

+0

不要忘記首先測試兩個列表的長度爲提高速度,當兩個列表的大小不同。 – 2014-11-06 20:02:44

+0

@StevenRumbalski - 好主意。我會執行它。 – iCodez 2014-11-06 20:13:57

4

浮現在腦海中的兩種方法是:

1)使用collections.Counter

>>> from collections import Counter 
>>> Counter(alist) == Counter(anotherList) 
True 

2)比較排序列表

>>> sorted(alist) == sorted(anotherList) 
True 
+0

'計數器'解決方案很好,因爲它是線性的O(n)而不是O(n log n)。 – 2014-11-06 19:28:35

+1

@JohnKugelman - 對於較小的列表,「排序」解決方案的速度很快*。運行一個簡單的'timeit'測試可以爲'Counter'產生'36.708395899478845','sorted'則產生'3.7142343510138858'。我只會建議使用'Counter'作爲大型列表。 – iCodez 2014-11-06 19:34:03

+0

@iCodez在沒有重複的情況下,使用它會更快,返回set(alist)== set(anotherList)? – MarcSM23 2014-11-06 20:02:46

0

如果沒有重複,使用set,它沒有訂單:

set(alist) == set(anotherList) 
+0

-0。設置不起作用,因爲'set([1,2,3,])== set([1,1,2,3])'。 – 2014-11-06 19:40:52

+0

@StevenRumbalski:不需要急,請*閱讀*我的答案。 – 2014-11-06 19:45:34

+0

夠公平的。我仍然偏愛使用'sorted'或'Counter',因爲它可以工作,不管是否有重複。 – 2014-11-06 19:54:25

0

嘗試這樣的:

def check(a,b): 
    return sorted(a) == sorted(b) 
相關問題