过滤出字典中年龄小于20的姓名 people=[ {"name":"cyh","age":42}, {"name":"clm","age":13}, {"name":"stu","age":18} ]
时间: 2023-07-08 09:52:35 浏览: 119
可以使用列表推导式来过滤出年龄小于20的姓名。代码如下:
```python
people = [{"name":"cyh","age":42}, {"name":"clm","age":13}, {"name":"stu","age":18}]
names = [person["name"] for person in people if person["age"] < 20]
print(names)
```
输出结果为:`['clm', 'stu']`。
相关问题
用filter函数过滤出字典中年龄小于20的姓名 people = [{"name":"cyh","age":42}, {"name":"clm","age":13}, {"name":"stu","age":18}]
可以使用 `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']`。
阅读全文