1.使用循环(保留原顺序)

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]

2.使用字典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]

3.使用集合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]

Q.E.D.


Nothing really matters to me!