编写python程序,利用del()函数,将列表中相同的元素只保留一个。 如 ['b','c','d','b','c','a','a'] ,改为['b','c','d','a']
lst = ['b', 'c', 'd', 'b', 'c', 'a', 'a'] new_lst = list(set(lst)) print(new_lst) # ['a', 'c', 'b', 'd'],元素的顺序可能不一致,因为set是无序的
如果要保持原来的顺序,可以用以下方法
new_lst = [] for item in lst: if item not in new_lst: new_lst.append(item) print(new_lst) # ['b', 'c', 'd', 'a']
原文地址: https://www.cveoy.top/t/topic/vDb 著作权归作者所有。请勿转载和采集!