Python 列表去重
时间: 2023-11-05 13:06:14 浏览: 96
Python 列表去重可以使用 set() 函数。具体操作如下:
```python
my_list = [1, 2, 3, 3, 4, 4, 5]
my_list = list(set(my_list))
print(my_list)
```
输出结果为:
```python
[1, 2, 3, 4, 5]
```
也可以使用列表推导式实现去重操作:
```python
my_list = [1, 2, 3, 3, 4, 4, 5]
my_list = [x for i, x in enumerate(my_list) if x not in my_list[:i]]
print(my_list)
```
输出结果为:
```python
[1, 2, 3, 4, 5]
```
相关问题
python 列表去重
Python 中可以通过 set() 函数实现列表去重,具体代码如下:
```
lst = [1, 2, 2, 3, 3, 4, 5, 5]
new_lst = list(set(lst))
print(new_lst) # [1, 2, 3, 4, 5]
```
另外,也可以使用列表推导式实现列表去重:
```
lst = [1, 2, 2, 3, 3, 4, 5, 5]
new_lst = []
[new_lst.append(i) for i in lst if i not in new_lst]
print(new_lst) # [1, 2, 3, 4, 5]
```
python列表去重
去重是列表常见的操作之一,Python中可以使用set()函数来进行去重操作。具体实现方式如下:
```python
a = [1, 2, 3, 3, 4, 4, 5]
b = list(set(a))
print(b)
```
输出结果为:
```
[1, 2, 3, 4, 5]
```
其中,set()函数可以将列表转化为集合,集合中的元素必须是不可变的,因此set()函数可以去除列表中的重复元素。最后再将集合转化为列表即可。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)