python – 获取列表中的所有非唯一元素
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 获取列表中的所有非唯一元素,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1433字,纯文字阅读大概需要3分钟。
内容图文
![python – 获取列表中的所有非唯一元素](/upload/InfoBanner/zyjiaocheng/728/595beb8b4d1447bfaab81cb7c77e9771.jpg)
我正在尝试构建一个代码,该代码返回一个包含非唯一值的列表,例如[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
这些是测试示例:
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]
解决方法:
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]
测试:
>>> 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]
内容总结
以上是互联网集市为您收集整理的python – 获取列表中的所有非唯一元素全部内容,希望文章能够帮你解决python – 获取列表中的所有非唯一元素所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。