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

后端 未结 5 1767
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

    0 讨论(0)
  • 2021-01-15 21:20
    def distinct(lst):
        dlst = []
        for val in lst:
            if val not in dlst:
                dlst.append(val)
        return dlst
    
    0 讨论(0)
  • 2021-01-15 21:25

    If order isn't important, you can cast it to a set, then back to a list

    def distinct(lst):
        return list(set(lst))
    
    0 讨论(0)
  • 2021-01-15 21:29

    Is this considered cheating?

    >>> distinct = lambda lst: list(set(lst))
    >>> distinct([1,3,1,2,6])
    [1, 2, 3, 6]
    >>> distinct(['a','ab','a','ab'])
    ['a', 'ab']
    
    0 讨论(0)
  • 2021-01-15 21:41

    There are Excellent Solutions That I Already Applied. But my professor said us that we don't must use the methods of the list. Has anyone else got any more thoughts?

    0 讨论(0)
提交回复
热议问题