python除了用set怎么集合去重
时间: 2023-04-06 10:03:51 浏览: 91
你可以使用列表推导式或者使用for循环来实现集合去重。例如,使用列表推导式可以这样写:list(set([1, 2, 2, 3, 3, 4])),使用for循环可以这样写:result = [] for item in [1, 2, 2, 3, 3, 4]: if item not in result: result.append(item)。
相关问题
python怎么用集合去重
使用集合可以很方便地进行去重操作,可以使用以下代码实现:
```
list_with_duplicates = [1, 2, 3, 1, 2, 4, 5, 6, 5]
unique_items = set(list_with_duplicates)
print(unique_items)
```
输出结果为: {1, 2, 3, 4, 5, 6}
python集合去重
以下是Python中集合去重的方法:
1.使用set()函数去重
```python
list1 = ['a', 'b', 1, 3, 9, 9, 'a']
set1 = set(list1)
print(set1) # 输出:{'a', 1, 3, 'b', 9}
```
2.使用列表转集合再转回列表的方式去重
```python
list1 = ['a', 'b', 1, 3, 9, 9, 'a']
list2 = list(set(list1))
print(list2) # 输出:['a', 1, 3, 'b', 9]
```
3.使用列表推导式去重
```python
list1 = ['a', 'b', 1, 3, 9, 9, 'a']
list2 = list(set([i for i in list1]))
print(list2) # 输出:['a', 1, 3, 'b', 9]
```
4.使用字典去重
```python
list1 = ['a', 'b', 1, 3, 9, 9, 'a']
dict1 = {}.fromkeys(list1)
list2 = list(dict1.keys())
print(list2) # 输出:['a', 'b', 1, 3, 9]
```
5.使用numpy库去重
```python
import numpy as np
list1 = ['a', 'b', 1, 3, 9, 9, 'a']
arr1 = np.array(list1)
arr2 = np.unique(arr1)
list2 = arr2.tolist()
print(list2) # 输出:['1', '3', '9', 'a', 'b']
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)