如何用Pythonic方法找出与参考列表共享元素最多的列表
Python风格实现:找出与参考列表共享元素最多的列表
我有一个参考列表,还有一组长度不同的列表,想要从中选出和参考列表共享元素数量最多的单个列表返回。有没有更具Python风格的实现方式?以下是我的数据结构及尝试代码:
reference_list = [(0, 0), (3, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (15, 19), (15, 20)] list_1 = [(7, 7), (8, 8), (9, 9), (10, 10)] list_2 = [(6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (15, 19), (15, 20)] list_3 = [(0, 0), (7, 7), (10, 10), (15, 19), (15, 20)] list_4 = [(2, 2), (8, 8), (9, 9), (7, 7), (8, 8), (9, 9)] # list_5 = [(5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (15, 19), (15, 20)] # list_6 = [(0, 0), (3, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (15, 19), (15, 20)] list_of_lists = (list_1, list_2, list_3, list_4) # , list_5)#, list_6) counts = [] for list_element in list_of_lists: count = 0 print(list_element) lengh_of_element = len(list_element) for i in range(lengh_of_element): if list_element[i] in reference_list: count += 1 counts.append(count) maximum_count = max(counts) max_count_index = counts.index(maximum_count) selected_list = list_of_lists[max_count_index] print('the list with maximum number of shared elements with the reference list is: list_', max_count_index+1)
更Pythonic的实现方式
可以利用集合的快速查找特性和内置函数的高阶用法来简化代码,同时提升效率:
reference_set = set(reference_list) list_of_lists = (list_1, list_2, list_3, list_4) # 找到交集元素最多的列表 best_list = max(list_of_lists, key=lambda lst: len(set(lst) & reference_set)) # 获取对应下标并输出 best_index = list_of_lists.index(best_list) + 1 print(f"与参考列表共享元素最多的是:list_{best_index}")
优化说明
- 集合转换:把
reference_list转为集合reference_set,将元素查找的时间复杂度从O(n)降到O(1),大规模数据下效率提升明显。 - max函数的key参数:通过lambda表达式直接计算每个列表与参考集合的交集长度,作为排序依据,一步到位找到最优列表,无需手动遍历计数。
- 简洁性:去掉冗余的嵌套循环和计数列表,代码更紧凑易读,符合Python的“简洁优雅”风格。
如果需要处理多个列表交集数量相同的情况,可以用列表推导式找出所有候选列表:
max_common = max(len(set(lst) & reference_set) for lst in list_of_lists) best_lists = [lst for lst in list_of_lists if len(set(lst) & reference_set) == max_common]
内容的提问来源于stack exchange,提问作者bluered_earth
相关产品推荐
相关产品推荐

