在Python中,求两个集合的交集可以通过以下几种方法:
1. 使用集合的交集方法:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection = set1.intersection(set2)
print("交集结果:", intersection)
2. 使用列表推导式:
b1 = [1, 2, 3]
b2 = [2, 3, 4]
intersection = [val for val in b1 if val in b2]
print(intersection)
3. 使用集合操作符 `&`:
b1 = [1, 2, 3]
b2 = [2, 3, 4]
intersection = list(set(b1) & set(b2))
print(intersection)
4. 使用 `filter()` 函数和 `lambda` 表达式:
b1 = [1, 2, 3]
b2 = [2, 3, 4]
intersection = list(filter(lambda x: x in b2, b1))
print(intersection)
5. 对于嵌套类型的列表,可以使用类似的方法:
b1 = [1, 2, 3]
b2 = [[2, 4], [3, 5]]
intersection = [val for sublist in b2 for val in sublist if val in b1]
print(intersection)
以上方法都可以用来求两个集合的交集。选择哪种方法取决于具体的应用场景和个人偏好
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/117418.html