python 列表(List)求交集

1、利用集合set

1.1 使用 intersection 方法获取交集

list1 = [1, 2, 3]
list2 = [1, 2]

common_list = set(list1).intersection(set(list2))
print(list(common_list))  # [1, 2]

注意:集合是无序的,所以common_list中元素的顺序与原列表可能不同。

1.2 使用 & 运算符获取交集

list1 = [1, 2, 3]
list2 = [1, 2]

common_list = set(list1) & (set(list2))
print(list(common_list))  # [1, 2]

2、利用列表解析:有序

common_list = [x for x in list1 if x in list2]

注意:虽然有序了,但是这个操作相较于用set会慢,特别是当列表元素很多时。


发表评论

评论列表,共 1 条评论

  • ivadebtsource.co.uk

    That is very fascinating, You're a very skilled blogger. I have joined your rss feed and look forward to searching for more of your great post. Additionally, I have shared your web site in my social networks