python列表去重复
时间: 2023-10-15 09:25:00 浏览: 38
要在Python中去除列表中的重复项,可以使用set函数。set函数会自动去除重复的元素,并返回一个新的列表。以下是一个示例代码:
```python
my_list = [1, 2, 2, 3, 4, 4, 5]
new_list = list(set(my_list))
print(new_list)
```
运行结果会输出:[1, 2, 3, 4, 5],即去除了原列表中的重复项。
相关问题
python 列表去重复
在Python中,可以使用多种方法对列表进行去重。以下几种常见的方法:
1. 使用set()函数:将列表转换为集合,集合的特性是元素不重复,然后再将集合转换回列表。这种方法会改变原始列表的顺序。
```python
my_list = [1, 2, 3, 3, 4, 5, 5]
new_list = list(set(my_list))
print(new_list)
```
2. 使用列表推导式:通过遍历原始列表,将不重复的元素添加到新列表中。
```python
my_list = [1, 2, 3, 3, 4, 5, 5]
new_list = []
[new_list.append(x) for x in my_list if x not in new_list]
print(new_list)
```
3. 使用字典:遍历原始列表,将元素作为字典的键,值可以是任意值。由于字典的键是唯一的,重复的元素会被自动去除。然后再将字典的键转换为列表。
```python
my_list = [1, 2, 3, 3, 4, 5, 5]
new_list = list(dict.fromkeys(my_list))
print(new_list)
```
4. 使用collections模块中的OrderedDict类:OrderedDict是一个有序字典,遍历原始列表,将元素作为OrderedDict的键,值可以是任意值。由于OrderedDict的键是唯一的,重复的元素会被自动去除。然后再将OrderedDict的键转换为列表。
```python
from collections import OrderedDict
my_list = [1, 2, 3, 3, 4, 5, 5]
new_list = list(OrderedDict.fromkeys(my_list))
print(new_list)
```
这些方法都可以实现对列表的去重,选择哪种方法取决于你的需求和个人偏好。
python列表去除重复值
你可以使用以下两种方法来去除 Python 列表中的重复值:
1. 使用 set() 函数
将列表转换为集合可以很容易地删除任何重复值,然后将其转换回列表。
例如:
my_list = [1, 2, 2, 3, 3, 4, 5, 6, 6, 7]
new_list = list(set(my_list))
print(new_list)
输出:[1, 2, 3, 4, 5, 6, 7]
2. 使用循环
如果你不想改变列表的顺序,可以使用循环,从而删除重复值。
例如:
my_list = [1, 2, 2, 3, 3, 4, 5, 6, 6, 7]
new_list = []
for i in my_list:
if i not in new_list:
new_list.append(i)
print(new_list)
输出:[1, 2, 3, 4, 5, 6, 7]
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)