有勇气的牛排博客

Python合并列表并去重

有勇气的牛排 562 Python 2024-09-22 21:18:37

1 兩個簡單的案例

A = [1, 3, 2] B = [3, 4, 5] C = A + B print(set(C)) print(list(set(C))) print(dict.fromkeys(C)) print(list(dict.fromkeys(C)))

Python合并列表并去重

2 萬物節可util

https://www.couragesteak.com/article/481

class UtilList: # 合并多个列表 保持原顺序 去重 @staticmethod def merge_list_order(*lists): """ fromkeys 在 Python 3.7 及以上版本中,字典保持插入顺序 """ return list(dict.fromkeys(item for lst in lists for item in lst)) # 合并多个列表 去重 不考虑顺序 @staticmethod def merge_list_unorder(*lists): """ set 使用 哈希表来存储元素 :param lists: :return: """ return list(set(item for lst in lists for item in lst)) A = [1, 3, 2] B = [3, 4, 5] # 保持原顺序去重 res_order = UtilList.merge_list_order(A, B) print("保持原顺序 去重:", res_order) # 输出: [1, 3, 2, 4, 5] # 不考虑顺序去重 res_un_order = UtilList.merge_list_unorder(A, B) print("不考虑顺序 去重:", res_un_order) # 输出: [1, 2, 3, 4, 5]

留言

专栏
文章
加入群聊