Python合并列表并去重
知止自律打卡-微信小程序APP
一款微信自律打卡小程序,支持自定义打卡项目、习惯记录、项目日记、专注计时与数据统计。自律打卡、学习打卡、读书打卡、健身打卡、运动打卡、减肥打卡、戒色打卡、养生打卡、戒烟、戒酒、戒熬夜等多种场景。万能打卡模板自由创建。可自定义每日打卡目标,记录习惯连续天数,可视化追踪成长进度。
了解产品详情 →
微信搜索「知止自律打卡」
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)))

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]
标签: