python获取重复元素
【摘要】
这个不错:
from collections import Counter # 引入Counter list = [29, 36, 57, 12, 79, 43, 23, 56, 28, 11, 14, 15, 16, 37, 24, 35, 17, 24, 33, 15, 39, 46, 52, 13] set = set(list) for item ...
这个不错:
-
from collections import Counter # 引入Counter
-
-
list = [29, 36, 57, 12, 79, 43, 23, 56, 28, 11, 14, 15, 16, 37, 24, 35, 17, 24, 33, 15, 39, 46, 52, 13]
-
-
set = set(list)
-
-
for item in set:
-
-
print("the %d has found %d" %(item,list.count(item)))
Counter:
-
from collections import Counter # 引入Counter
-
-
list = [29, 36, 57, 12, 79, 43, 23, 56, 28, 11, 14, 15, 16, 37, 24, 35, 17, 24, 33, 15, 39, 46, 52, 13]
-
-
aaa= Counter(list)
-
-
print(aaa)
可以根据上面的自己加工,想直接抄代码的,下面这个可以:
-
from collections import Counter # 引入Counter
-
-
a = [29, 36, 57, 12, 79, 43, 23, 56, 28, 11, 14, 15, 16, 37, 24, 35, 17, 24, 33, 15, 39, 46, 52, 13]
-
b = dict(Counter(a))
-
print([key for key, value in b.items() if value > 1]) # 只展示重复元素
-
print({key: value for key, value in b.items() if value > 1}) # 展现重复元素和重复次数
测试结果展示:
[15, 24]
{15: 2, 24: 2}
文章来源: blog.csdn.net,作者:网奇,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/jacke121/article/details/108238291
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)