我的教授给了我一个练习,我在其中编写了一个函数,该函数返回一个没有与旧列表重复的列表。 这是代码,但我不知道如何在不使用 .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
