利用lambda表达式的复杂例子
时间: 2023-05-29 16:05:54 浏览: 69
假设有一个列表,其中包含多个字典,每个字典都有一个“名称”键和一个“年龄”键。我们想要按照年龄对这些字典进行排序,可以使用lambda表达式来实现:
```
people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 20}
]
sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)
```
输出结果为:
```
[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
```
这里的lambda表达式`lambda x: x["age"]`指定了按照每个字典的“age”键进行排序,相当于传递了一个函数给`sorted()`函数的`key`参数。
相关问题
利用lambda表达式的例子
1. 求和函数
```python
sum = lambda x, y: x + y
print(sum(2, 3)) # Output: 5
```
2. 列表排序
```python
students = [('Tom', 20), ('John', 15), ('Alex', 25)]
students.sort(key=lambda x: x[1])
print(students) # Output: [('John', 15), ('Tom', 20), ('Alex', 25)]
```
3. 过滤列表
```python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]
```
4. 列表映射
```python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
```
5. 匿名函数作为参数
```python
def my_function(numbers, func):
result = []
for number in numbers:
result.append(func(number))
return result
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_numbers = my_function(numbers, lambda x: x**2)
print(squared_numbers) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
```
Lambda 表达式C++例子
以下是一个使用Lambda表达式的C++例子:
```
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
int sum = 0;
// 使用Lambda表达式来计算向量v中所有偶数的和
std::for_each(v.begin(), v.end(), [&] (int n) {
if (n % 2 == 0) {
sum += n;
}
});
std::cout << "Sum of even numbers in vector is " << sum << std::endl;
return 0;
}
```
在这个例子中,使用Lambda表达式来计算向量v中所有偶数的和。Lambda表达式使用for_each算法来遍历向量v中的所有元素,如果元素是偶数,则将其添加到变量sum中。Lambda表达式使用了捕获列表[&],表示Lambda表达式可以访问当前作用域中的所有变量(包括sum)。最后,输出变量sum的值。
需要注意的是,Lambda表达式可以访问捕获列表中的变量,但不能修改它们的值,除非使用mutable关键字来声明Lambda表达式是可变的。
相关推荐
![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_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)