天天看點

python:五種方法去除清單的重複元素 list去重

# 去重
lst = [1, 2, 3, 2, 3, 4]
# 第一種  集合可以去重  先轉換成集合再轉換成清單
print("方法一:", list(set(lst)))

# 第二種
lst.sort()
del_lst = []
for i in range(len(lst) - 1):
    if lst[i] == lst[i + 1]:
        del_lst.append(lst[i + 1])
for j in del_lst:
    lst.remove(j)
print("方法二:", lst)

# 第三種
new_lst = []
for k in lst:
    if k not in new_lst:
        new_lst.append(k)
print("方法三:", new_lst)

# 第四種
# fromkeys 是把所有的鍵都賦同樣的值(如果不指定内容則預設指派為None)
lst1 = []
dct = dict.fromkeys(lst)
print(dct)
for n in dct:
    lst1.append(n)
print("方法四:", lst1)

# 第五種  第四種方法的簡寫
print("方法五:", list(dict.fromkeys(lst)))