filter python
时间: 2023-09-09 21:09:50 浏览: 107
The filter() function in Python is used to filter out elements from an iterable (e.g. list, tuple, dictionary) based on a certain condition. The syntax for filter() is:
```
filter(function, iterable)
```
The first argument, "function", is a function that takes in one argument and returns a boolean value (True or False). The second argument, "iterable", is an iterable object that will be filtered.
The filter() function returns a new iterable object (e.g. list, tuple) containing only the elements from the original iterable for which the function returns True.
Here is an example of using filter() to filter out even numbers from a list:
```
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = list(filter(lambda x: x % 2 == 1, my_list))
print(filtered_list)
# Output: [1, 3, 5, 7, 9]
```
In this example, we use the lambda function to check if each element in the list is odd (i.e. not divisible by 2). The filter() function returns a new list containing only the odd numbers from the original list.
相关推荐
![](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)