Python列表去重的几种方式

一、方法1

 代码如下 

ids = [1,2,3,3,4,2,3,4,5,6,1]
news_ids = []
for id in ids:
    if id not in news_ids:
        news_ids.append(id)
print news_ids

思路看起来比较清晰简单 ,也可以保持之前的排列顺序。

 

二、方法2

通过set方法进行处理

 代码如下 

ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = list(set(ids))

处理起来比较简单,使用了集合方法set进行处理,不过结果不会保留之前的顺序。

 

三、方法3

利用lambda匿名函数和 reduce 函数处理

 代码如下 
ids = [1,4,3,3,4,2,3,4,5,6,1]
func = lambda x,y:x if y in x else x + [y]
reduce(func, [[], ] + ids)

 

四、方法4

使用itertools模块

 代码如下 

import itertools
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids.sort()
it = itertools.groupby(ids)
for k, g in it:
    print k

 

五、无法保持原有顺序

 代码如下 

liebiao=set(liebiao)

 

六、while遍历去重

 代码如下 

def delRepeat(liebiao):
 for x in liebiao:
  while liebiao.count(x)>1:
   del liebiao[liebiao.index(x)]
 return liebiao

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 set() 函数将列表转换为集合,因为集合具有去重的功能,然后再将集合转换回列表即可去除重复元素。示例代码如下: ``` lst = [1, 2, 3, 2, 4, 1, 5, 3] lst = list(set(lst)) print(lst) ``` 输出结果为: ``` [1, 2, 3, 4, 5] ``` ### 回答2: Python 列表去重可以使用以下几种方法: 1. 使用集合(set)方法:将列表转换为集合,由于集合中的元素是唯一的,重复的元素会被自动去除,然后再将集合转换回列表。例如: ```python lst = [1, 2, 2, 3, 4, 4, 5] lst = list(set(lst)) print(lst) ``` 输出结果为:[1, 2, 3, 4, 5] 2. 使用列表推导式方法:通过列表推导式的方式创建一个新列表,只包含原列表中的唯一元素。例如: ```python lst = [1, 2, 2, 3, 4, 4, 5] lst = [x for i, x in enumerate(lst) if x not in lst[:i]] print(lst) ``` 输出结果为:[1, 2, 3, 4, 5] 3. 使用循环方法:通过循环遍历原列表中的元素,将不重复的元素添加到一个新列表中。例如: ```python lst = [1, 2, 2, 3, 4, 4, 5] new_lst = [] for x in lst: if x not in new_lst: new_lst.append(x) print(new_lst) ``` 输出结果为:[1, 2, 3, 4, 5] 以上是三种常见的去重方法,可以根据实际情况选择合适的方法。 ### 回答3: Python 列表去重可以通过多种方式实现。以下是其中几种常见的方法: 方法一:使用set()函数 利用set()函数可以将列表转换为集合,由于集合的特性是元素唯一,转换后的集合将自动去除重复元素,然后再将集合转换回列表。 示例代码: ``` lst = [1, 2, 3, 3, 4, 4, 5] lst = list(set(lst)) print(lst) # [1, 2, 3, 4, 5] ``` 方法二:使用列表推导式 使用列表推导式可以遍历列表,同时只添加未出现过的元素。 示例代码: ``` lst = [1, 2, 3, 3, 4, 4, 5] lst = list(set([x for x in lst])) print(lst) # [1, 2, 3, 4, 5] ``` 方法三:使用循环遍历 通过使用for循环遍历列表,判断元素是否已经存在于新列表中,如果不存在则添加到新列表中。 示例代码: ``` lst = [1, 2, 3, 3, 4, 4, 5] new_lst = [] for x in lst: if x not in new_lst: new_lst.append(x) print(new_lst) # [1, 2, 3, 4, 5] ``` 这些方法都可以有效地去重,并根据实际需求选择适合的方法来处理列表中的重复元素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值