Delete unique elements from a list

前端 未结 9 1225
[愿得一人]
[愿得一人] 2020-12-10 09:20

I faced some problem with solving the next problem:

We have a list of elements (integers), and we should return a list consisting of only the non-unique elements in

相关标签:
9条回答
  • 2020-12-10 10:16

    Would it not be easier to generate a new list?

    def unique_list(lst):
        new_list = []
        for value in lst:
            if value not in new_list:
                new_list.append(value)
        return new_list
    
    lst = [1,2,3,1,4,5,1,6,2,3,7,8,9]
    print(unique_list(lst))
    

    Prints [1,2,3,4,5,6,7,8,9]

    0 讨论(0)
  • 2020-12-10 10:17

    Just I used list Comprehensions.

    def checkio(data):
        a=[i for i in data if data.count(i)>1]
        return a
    print checkio([1,1,2,2,1,1,1,3,4,5,6,7,8]) 
    
    0 讨论(0)
  • 2020-12-10 10:25

    Your function can be made to work by iterating over the list in reverse:

    def checkio(data):
        for index in range(len(data) - 1, -1, -1):
            if data.count(data[index]) == 1:
                del data[index]
        return data
    
    print(checkio([3, 3, 5, 8, 1, 4, 5, 2, 4, 4, 3, 0]))
    [3, 3, 5, 4, 5, 4, 4, 3]
    print(checkio([1, 2, 3, 4]))
    []
    

    This works, because it only deletes numbers in the section of the list that has already been iterated over.

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