python集合去重
时间: 2023-11-29 15:45:38 浏览: 88
利用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']
```
阅读全文