使用list项作为键创建dict,这将自动删除任何重复项,因为dict不能有重复的键,保留原顺序。
old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = list(dict.fromkeys(old_list))
print(new_list) # [2, 3, 4, 5, 1]
本文介绍了如何使用Python字典的特性,通过`dict.fromkeys()`方法将列表`old_list`中的重复元素去除,同时保持原有顺序,最终得到新的列表`new_list`,示例 `[2,3,4,5,1]`。
使用list项作为键创建dict,这将自动删除任何重复项,因为dict不能有重复的键,保留原顺序。
old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = list(dict.fromkeys(old_list))
print(new_list) # [2, 3, 4, 5, 1]

被折叠的 条评论
为什么被折叠?