用filter函数过滤出字典中年龄小于20的姓名 people = [{"name":"cyh","age":42}, {"name":"clm","age":13}, {"name":"stu","age":18}]
时间: 2023-07-08 22:52:35 浏览: 186
使用filter对字符进行过滤
可以使用 `filter` 函数和 `lambda` 表达式来过滤出年龄小于20的姓名。代码如下:
```python
people = [{"name":"cyh","age":42}, {"name":"clm","age":13}, {"name":"stu","age":18}]
names = list(filter(lambda person: person["age"] < 20, people))
print(names)
```
输出结果为:`[{"name":"clm","age":13}, {"name":"stu","age":18}]`。
如果只想得到姓名,可以在 `lambda` 表达式中返回 `person["name"]`,代码如下:
```python
people = [{"name":"cyh","age":42}, {"name":"clm","age":13}, {"name":"stu","age":18}]
names = list(filter(lambda person: person["age"] < 20, people))
names = [person["name"] for person in names]
print(names)
```
输出结果为:`['clm', 'stu']`。
阅读全文