[英]find duplicates in multiple list and return the count of duplicates for each list in Python
There are multiple lists,有多个列表,
[1,2], [2,3,4], [3,4,5], [6,8,9,10]... [1,2], [2,3,4], [3,4,5], [6,8,9,10]...
Is there a way to find and count duplicates for each list?有没有办法为每个列表查找和计算重复项? so for lists above, I want to get:所以对于上面的列表,我想得到:
[1,2] --- 1 duplicate which is 2 [1,2] --- 1 个重复,即 2
[2,3,4] --- 3 duplicates which are 2,3,4 [2,3,4] --- 3 个重复,即 2,3,4
[3,4,5] --- 2 duplicates which are 3, 4 [3,4,5] --- 2 个重复,即 3, 4
[6,7,8,9] - 0 duplicate [6,7,8,9] - 0 个重复
I am thinking that I can find the duplicates, then compare each list against duplicates and get the results.我在想我可以找到重复项,然后将每个列表与重复项进行比较并获得结果。
Is there a better/faster way to do it?有更好/更快的方法吗? Thanks for any suggestions.感谢您的任何建议。
Sure, there's a way to do this.当然,有办法做到这一点。
First, put your lists into a list.首先,将您的列表放入列表中。
list_of_lists = [[1,2], [2,3,4], [3,4,5], [6,8,9,10]]
Then, figure out all the items you have:然后,找出你拥有的所有物品:
all_items = [n for l in list_of_lists for n in l]
Then figure out which items are duplicated:然后找出哪些项目是重复的:
duplicates = set([n for n in all_items if all_items.count(n) > 1])
Then calculate duplicates for each list:然后计算每个列表的重复项:
for l in list_of_lists:
duplicate_count = len([n for n in l if n in duplicates])
print("Duplicates: ", duplicate_count)
Incidentally, I think you want 3
for the second answer, since both 2, 3, and 4 are all duplicated in your lists.顺便说一句,我认为您想要3
作为第二个答案,因为 2、3 和 4 在您的列表中都是重复的。
Duplicates: 1
Duplicates: 3
Duplicates: 2
Duplicates: 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.