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']
.
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 :
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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.