获取列表中的所有非唯一元素

Ela*_*erg 3 python list python-3.x

我正在尝试构建一个代码,该代码返回一个包含非唯一值的列表,例如[1,2,2,3]=>,[2,2]并且该函数不区分大小写,例如:['p','P','a','b',1,5,6]=> ['p','P'].

这是我到目前为止所提出的:

def non_unique(*data):
    tempLst = [x for x in data if (data.count(x) > 1 if (ord('a') <= ord(x) <= ord('z') or ord('A') <= ord(x) <= ord('Z')) and (data.count(x.upper()) + data.count(x.lower()) > 1)]
    return tempLst
Run Code Online (Sandbox Code Playgroud)

这些是测试示例:

if __name__ == "__main__":
    assert isinstance(non_unique([1]), list)
    assert non_unique([1, 2, 3, 1, 3]) == [1, 3, 1, 3]
    assert non_unique([1, 2, 3, 4, 5]) == []
    assert non_unique([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
    assert non_unique([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9]


    assert non_unique(['P', 7, 'j', 'A', 'P', 'N', 'Z', 'i',
                   'A', 'X', 'j', 'L', 'y', 's', 'K', 'g',
                   'p', 'r', 7, 'b']) == ['P', 7, 'j', 'A', 'P', 'A', 'j', 'p', 7]
Run Code Online (Sandbox Code Playgroud)

ffe*_*rri 5

集合中使用Counter:

from collections import Counter

def non_unique(l):
    def low(x):
        return x.lower() if isinstance(x, str) else x
    c = Counter(map(low, l))
    return [x for x in l if c[low(x)] > 1]
Run Code Online (Sandbox Code Playgroud)

测试:

>>> non_unique([1, 2, 3, 1, 3])
[1, 3, 1, 3]
>>> non_unique([1, 2, 3, 4, 5])
[]
>>> non_unique([5, 5, 5, 5, 5])
[5, 5, 5, 5, 5]
>>> non_unique([10, 9, 10, 10, 9, 8])
[10, 9, 10, 10, 9]
>>> non_unique(['P', 7, 'j', 'A', 'P', 'N', 'Z', 'i',
...                    'A', 'X', 'j', 'L', 'y', 's', 'K', 'g',
...                    'p', 'r', 7, 'b'])
['P', 7, 'j', 'A', 'P', 'A', 'j', 'p', 7]
Run Code Online (Sandbox Code Playgroud)