首页 >后端开发 >Python教程 >如何在Python中高效地查找嵌套列表的交集?

如何在Python中高效地查找嵌套列表的交集?

Barbara Streisand
Barbara Streisand原创
2024-12-04 05:40:11319浏览

How Can I Efficiently Find Intersections of Nested Lists in Python?

查找嵌套列表的交集

从嵌套列表中检索交集提出了与平面列表的直接方法不同的挑战。本文探讨了一种有效确定嵌套列表交集的解决方案。

如问题内容所示,使用集合交集可以轻松实现查找平面列表的交集:

b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
print(set(b1) & set(b2))  # Output: {4, 5}

但是,当处理嵌套列表时,例如:

c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

简单的方法无法产生所需的结果结果:

print(set(c1) & set(c2))  # Output: set([])

我们目标的交集是:

c3 = [[13, 32], [7, 13, 28], [1, 6]]

解决方案:

解决方案在于将嵌套列表转换为集合,执行集合交集,然后重建原始嵌套列表结构:

# Convert nested lists to sets 
set_c1 = set(c1) 
set_c2 = [set(sublist) for sublist in c2]

# Compute intersections
intersections = [set_c1.intersection(sublist) for sublist in set_c2]

# Reconstruct nested list structure 
result = [[item for item in intersection] for intersection in intersections] 

# Print the result
print(result)  # Output: [[13, 32], [7, 13, 28], [1, 6]]

通过利用集合交集和集合理解,该解决方案有效地检索嵌套列表的交集,保留其结构。

以上是如何在Python中高效地查找嵌套列表的交集?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn