How can I write a list without duplicate with only for, if and boolean

后端 未结 5 1771
Happy的楠姐
Happy的楠姐 2021-01-15 20:46

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 meth

5条回答
  •  暖寄归人
    2021-01-15 21:16

    If you need to eliminate duplicates AND preserve order you can do this:

    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']
    

    See a demo here: https://ideone.com/a2khCg

提交回复
热议问题