在Python中,删除列表中的重复数据可以通过以下几种方法:
1. 使用`set()`函数:
python
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. 使用列表推导式:
python
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`从列表中删除重复项(保留顺序):
python
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`方法保持原有顺序:
python
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']
5. 使用遍历创建切片来删除原列表中的重复项:
python
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`方法可以保持原有顺序。如果需要保留原始顺序,请选择适当的方法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/42910.html