在Python中,删除列表中的重复数据可以通过以下几种方法:
1. 使用`set()`函数:
my_list = [1, 2, 3, 3, 4, 5, 5, 6]
new_list = list(set(my_list))
print(new_list) 输出结果:[1, 2, 3, 4, 5, 6]
2. 使用列表推导式:
my_list = [1, 2, 3, 3, 4, 5, 5, 6]
new_list = [x for i, x in enumerate(my_list) if x not in my_list[:i]]
print(new_list) 输出结果:[1, 2, 3, 4, 5, 6]
3. 使用`OrderedDict`从列表中删除重复项(保留顺序):
from collections import OrderedDict
mylist = ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
resList = OrderedDict.fromkeys(mylist)
print(list(resList)) 输出结果:['Jacob', 'Harry', 'Mark', 'Anthony']
4. 使用`sorted()`函数和`index`方法保持原有顺序:
my_list = ['b', 'c', 'd', 'b', 'c', 'a', 'a']
new_list = sorted(set(my_list), key=my_list.index)
print(new_list) 输出结果:['a', 'b', 'c', 'd']
l1 = [1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
l2 = []
for el in l1[:]:
if l1.count(el) > 1:
l1.remove(el)
else:
l2.append(el)
print(l2) 输出结果:[1, 2, 3, 6, 5]
以上方法各有优缺点,可以根据具体需求选择合适的方法。需要注意的是,使用`set()`函数或`OrderedDict`会丢失原始列表的顺序,而使用`sorted()`函数和`index`方法可以保持原有顺序。如果需要保留原始顺序,请选择适当的方法