2014-05-21 32 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))方法,除非你有一个特定的用例禁止它。

相关问题