.distinct()
时间: 2023-09-24 09:05:55 浏览: 73
The .distinct() method is a method in Python that returns a new list or set containing only the unique elements of the original list. It eliminates duplicates and returns a new list with distinct elements.
For example, consider the following list:
```python
my_list = [1, 2, 2, 3, 4, 4, 5]
```
If we apply the .distinct() method to this list, it will remove the duplicate elements and return the following list:
```python
new_list = my_list.distinct()
print(new_list)
```
Output:
```python
[1, 2, 3, 4, 5]
```
Note that .distinct() works only for lists containing hashable elements. If the list contains unhashable elements like lists or dictionaries, it will raise a TypeError. In such cases, we can use other methods like loop or set comprehension to get the distinct elements.
相关推荐
![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)
![](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)