2014-05-21 29 views

回答

1

使用設置,使值唯一:

cleaned_A = list(set(A)) 
+0

'我知道remove()方法或將列表A轉換爲set' - 來自問題。 – thefourtheye

1

你可以將其轉換成一組,然後返回到一個列表中刪除重複。試試這個:

>>> A = [1,2,2,2,3] 
>>> A = list(set(A)) 
>>> A 
[1, 2, 3] 
+0

'我知道remove()方法或將列表A轉換爲set' - 來自問題。 – thefourtheye

+0

哦...對不起... – anirudh

1

將其轉換爲set然後回到list這樣:

cleaned_A = list(set(A)) 
+0

'我知道remove()方法或將列表A轉換爲set' - 來自問題。 – thefourtheye

+0

我認爲這可能是最好的方法.. – AndyLiu

1

沒有套

>>> list({}.fromkeys(A)) 
[1, 2, 3] 
0

試試這個。

>>> A = [1,2,2,2,3] 
>>> reduce(lambda seen, item: seen + [item] if item not in seen else seen, A, []) 
[1, 2, 3] 
1

那麼該解決方案必須是至少O(N),因爲你必須檢查列表中的所有項目至少一次。

因此,可以說A = [1,2,2,2,3]

cleaned_A = set() 
for i in A: 
    cleaned_A.add(i) 
0

這不會是我的第一選擇,但你可以list.index和list.pop刪除項目已經在列表中早些存在。這樣你保持原來的結構。

A = [1,2,2,2,3] 
i = len(A) - 1 
while i >= 0: 
    if A.index(A[i]) != i: 
     A.pop(i) 
    i -= 1 

但是,多次修改列表更加昂貴,從頭開始構建新的列表一次。這個方法已經是O(N^2)。

我建議只使用列表(set(A))方法,除非你有一個特定的用例禁止它。

相關問題