[英]Combine lists that have at least a number in common in a list of lists, Python
[英]is it possible to have lists with the maximum number of common integers?
我有一个包含多个整数列表的列表,我想找到具有最大公共元素的列表。
我尝试使用交集,但它返回一个空集,因为这里的交集涉及在我的列表中找到的所有列表的公共元素。 我希望我的代码向我显示具有我想要的公共 integer 号码的列表。 例如,如果我想要列表有 3 个共同的整数,它会向我显示有问题的列表。 我在 .net 上搜索了很多,但我只能找到确定两个列表是否相同的推理。
这是交集的代码:
import string
list = [[3,5,9], [4,6,6], [4,7], [2,7], [2,1,4,5], [1,2,4,6], [3,3], [3,3], [3,2,1], [3,2]]
result = set.intersection(*map(set,list))
print(result)
这是结果:
set()
但我想要的是:
[2,1,4,5],[1,2,4,6]
您想要的是根据交集中有 3 个项目的条件过滤列表对。
您可以使用itertools.combinations
获取所有对,并使用列表理解过滤它们:
import string
from itertools import combinations
list_ = [[3,5,9], [4,6,6], [4,7], [2,7], [2,1,4,5], [1,2,4,6], [3,3], [3,3], [3,2,1], [3,2]]
print([c for c in combinations(list_, r=2) if len(set(c[0]) & set(c[1])) == 3])
output 应要求:
[([2, 1, 4, 5], [1, 2, 4, 6])]
我对你的措辞有点困惑,但我认为这就是你要找的:
data = [[3, 5, 9], [4, 6, 6], [4, 7], [2, 7], [2, 1, 4, 5], [1, 2, 4, 6], [3, 3], [3, 3], [3, 2, 1], [3, 2]]
max_unique_elements = 0
holding = []
for data_list in data:
unique_elements = len(set(data_list))
if unique_elements > max_unique_elements:
holding = [data_list]
max_unique_elements = unique_elements
elif unique_elements == max_unique_elements:
holding.append(data_list)
print(holding)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.