我怎样才能写一个没有重复的列表,仅用于,如果和布尔
问题内容:
我的教授给了我一个练习,我编写了一个函数,该函数返回一个列表,但没有重复的列表到旧列表中。这是代码,但是我不知道如何使用.remove()
以下方法编写方法:
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']])
我忘了写一件重要的事情,我必须在输出列表中保留顺序。
[更新]在阅读Jai Srivastav的答案后,我将其编码为:
def distinct(lst):
lstnew = []
for element in lst:
if element not in lstnew:
lstnew = lstnew + [element]
return lstnew
而且效果很好
问题答案:
def distinct(lst):
dlst = []
for val in lst:
if val not in dlst:
dlst.append(val)
return dlst