如何仅使用 for、if 和 boolean 编写没有重复的列表 [英] How can I write a list without duplicate with only for, if and boolean
本文介绍了如何仅使用 for、if 和 boolean 编写没有重复的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的教授给了我一个练习,我编写了一个函数,该函数返回一个没有重复的列表到旧列表.这是代码,但我不知道如何在不使用 .remove()
的情况下编写该方法:
My professor gave me an exercise where I write a function that returns a list without the duplicate to the old list.
This is the code but I don't know how to write the method without using .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']])
我忘记写一个重要的东西,我必须在输出列表中保留顺序.
I forgot to write an important thing, I must preserve order in the output list.
[更新]在我阅读了 Jai Srivastav 的答案后,我对此进行了编码:
[UPDATE] After I read the answer of Jai Srivastav I code this:
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
这篇关于如何仅使用 for、if 和 boolean 编写没有重复的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文