溫馨提示×

python怎么刪除列表中相同的內(nèi)容

小億
98
2024-04-03 15:39:02
欄目: 編程語言

可以使用以下方法刪除列表中相同的內(nèi)容:

  1. 使用set()函數(shù)去除列表中的重復(fù)元素,然后再轉(zhuǎn)回列表形式:
my_list = [1, 2, 3, 1, 2, 3]
my_list = list(set(my_list))
print(my_list)
  1. 使用列表推導(dǎo)式去除重復(fù)元素:
my_list = [1, 2, 3, 1, 2, 3]
my_list = list(dict.fromkeys(my_list))
print(my_list)
  1. 使用循環(huán)遍歷列表,將不重復(fù)的元素添加到新列表中:
my_list = [1, 2, 3, 1, 2, 3]
new_list = []
for item in my_list:
    if item not in new_list:
        new_list.append(item)
print(new_list)

以上是幾種常用的方法,可以根據(jù)具體情況選擇合適的方法。

0