2016-08-01 19 views
1

我的教授給了我一個練習,我寫了一個函數,它返回一個沒有重複到舊列表的列表。 這是代碼,但我不知道怎麼寫的方法,而無需使用.remove()我如何寫一個沒有重複的列表,只有if和boolean

def distinct(lst): 
    lstnew = [] 
    c = range(len(lst)) 
    for i in range(len(lst)): 
     if i in range(len(lst)) != c: 
      lstnew += [i] 
      c += 1 
      return lstnew 

print distinct([1,3,1,2,6]) 
print distinct([['a','ab','a','ab']]) 

我忘了寫一件重要的事情,我必須在輸出列表中保持秩序。

[更新] 後,我讀的潔Srivastav我這個代碼的答案:

def distinct(lst): 
lstnew = [] 
for element in lst: 
    if element not in lstnew: 
     lstnew = lstnew + [element] 
return lstnew 

和它的作品完美

+0

您現在沒有使用'remove'。 –

+0

你想爲這兩個例子輸出什麼,只是'[1,3,2,6]'和'['a','ab']' - 輸出列表是否需要保持輸入列表? – jedwards

+0

性能是否重要?許多實現(通過O(n)列表遍歷來確定是否存在某些實現的實現)將非常緩慢,因此您不希望在現實生活中使用它們。 –

回答

3
def distinct(lst): 
    dlst = [] 
    for val in lst: 
     if val not in dlst: 
      dlst.append(val) 
    return dlst 
+0

對不起,但我不能使用追加 –

2

這被認爲是作弊?

>>> distinct = lambda lst: list(set(lst)) 
>>> distinct([1,3,1,2,6]) 
[1, 2, 3, 6] 
>>> distinct(['a','ab','a','ab']) 
['a', 'ab'] 
+0

不幸的是是 –

1

如果順序並不重要,可以將其轉換爲set,然後回list

def distinct(lst): 
    return list(set(lst)) 
+0

請注意,這不會保留輸入順序。 – jedwards

+1

@jedwards正如答案的第一行所指出的那樣 - '「如果訂單不重要」#: –

+0

Oh man,there was the whole time?我的錯。 – jedwards

0

如果你需要消除重複和保持秩序,你可以這樣做:

def distinct(lst): 
    seen = set() 
    for item in lst: 
     if item not in seen: 
      yield item 
      seen.add(item) 

a = [1,3,1,2,6] 

print(list(distinct(a))) 

[1,3,2,6] 

b = ['a','ab','a','ab'] 

print(list(distinct(b))) 

['a', 'ab'] 

在這裏看到一個演示:https://ideone.com/a2khCg

+0

不幸的是我不能使用列表的方法 –

+0

哦,我明白了。這是練習的一個限制,但在現實生活中,它會很好:)如果我考慮另一種解決方案,我會更新我的答案。 – Fabio

0

有優秀的解決方案,我已經應用。但我的教授說我們不必使用列表的方法。有沒有人有更多的想法?

相關問題