从列表中删除唯一元素 [英] Delete unique elements from a list

查看:79
本文介绍了从列表中删除唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在解决下一个问题时遇到了一些问题:

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 this list. Without changing order of the list I think the best way is to delete or remove all unique element.

请注意,我才刚刚开始学习python,并且只想要最简单的解决方案.

Take note that I just start to learn python and would like only the simplest solutions.

这是我的代码:

def checkio(data):
    for i in data:
        if data.count(i) == 1:    #if element seen in the list just ones, we delet this el
            ind = data.index(i)
            del data[ind]
    return data

推荐答案

可以通过反向遍历列表来使您的函数起作用:

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.

这篇关于从列表中删除唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆