共計 368 個字符,預計需要花費 1 分鐘才能閱讀完成。
可以使用以下方法刪除列表中相同的內容:
- 使用 set() 函數去除列表中的重復元素,然后再轉回列表形式:
my_list = [1, 2, 3, 1, 2, 3]
my_list = list(set(my_list))
print(my_list)
- 使用列表推導式去除重復元素:
my_list = [1, 2, 3, 1, 2, 3]
my_list = list(dict.fromkeys(my_list))
print(my_list)
- 使用循環遍歷列表,將不重復的元素添加到新列表中:
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)
以上是幾種常用的方法,可以根據具體情況選擇合適的方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完