Python中对列表list去重的4种实现方法
Python中对列表list去重自己写直接的方法保留原顺序。old_list = [2, 3, 4, 5, 1, 2, 3]new_list = []for i in old_list:if i not in new_list:new_list.append(i)print(new_list) # [2, 3, 4, 5, 1]用字典dict去重使用list项作为键创建dict,这将自动删除任何重
·
Python中对列表list去重
- 自己写直接的方法
保留原顺序。
old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = []
for i in old_list:
if i not in new_list:
new_list.append(i)
print(new_list) # [2, 3, 4, 5, 1]
- 用字典dict去重
使用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]
- 用集合set去重
将list转化为set再转化为list,利用set的自动去重功能,但不保证顺序。
old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = list(set(old_list))
print(new_list) # 不保证顺序:[1, 2, 3, 4, 5]
再加上列表中索引(index)的方法保证去重后的顺序不变。
old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = list(set(old_list))
new_list.sort(key=old_list.index)
print(new_list) # 保留顺序:[2, 3, 4, 5, 1]
更多推荐
已为社区贡献19条内容
所有评论(0)