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 = list({i for i in lst})
print(lst) 输出:[1, 2, 3, 4, 5]
3. 使用循环遍历:
```python
lst = [1, 2, 2, 3, 4, 4, 5]
new_lst = []
for i in lst:
if i not in new_lst:
new_lst.append(i)
print(new_lst) 输出:[1, 2, 3, 4, 5]
4. 使用`filter()`函数:
```python
lst = [1, 2, 2, 3, 4, 4, 5]
lst = list(filter(lambda x: lst.count(x) == 1, lst))
print(lst) 输出:[1, 2, 3, 4, 5]
5. 对于Pandas的DataFrame,可以使用`duplicated()`和`drop_duplicates()`方法:
```python
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 2, 3, 4, 4, 5]})
print(df.duplicated()) 返回布尔序列,表示重复行
df = df.drop_duplicates() 删除重复行
print(df) 输出:
A
0 1
1 2
3 3
4 4
5 5
以上方法都可以用来去除列表中的重复元素。选择哪种方法取决于你的具体需求和上下文