Delete unique elements from a list

前端 未结 9 1230
[愿得一人]
[愿得一人] 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题