简体   繁体   English

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

[英]Get all non-unique elements in a list

I am trying to build a code that returns me a list with non-unique values, such as [1,2,2,3] => [2,2] and the function isn't case-sensitive, such as: ['p','P','a','b',1,5,6] => ['p','P'] . 我正在尝试构建一个代码,该代码返回一个包含非唯一值的列表,例如[1,2,2,3] => [2,2]并且该函数不区分大小写,例如: ['p','P','a','b',1,5,6] => ['p','P']

This is what I have come up with so far: 这是我到目前为止所提出的:

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

These are the test examples: 这些是测试示例:

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]

Use Counter from collections : 集合中使用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]

Tests: 测试:

>>> 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]

So I havd come up with an answer: 所以我想出答案:

def non_unique(data):
    tempLst = []
    for letter in data:
        if type(letter) == type('a'):
            if letter.lower() in tempLst or letter.upper() in tempLst:
                tempLst.append(letter)
            elif data.count(letter.lower()) + data.count(letter.upper()) > 1:
                tempLst.append(letter)
        else:
            if data.count(letter) > 1:
                tempLst.append(letter)
    return tempLst

If anyone has a shorter version please comment :) 如果有人有更短的版本请评论:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM