简体   繁体   English

Lambda 过滤字典列表 Python

[英]Lambda filter a list of dictionaries Python

I started programming with python a little while ago I have a doubt with dictionary不久前我开始用 python 编程我对字典有疑问

I have this array and I already have a method that gets an id array, I tried with lambda to create a filtered list, My question is if in addition to the filtered list I can leave in the list only the necessary attributes as the example我有这个数组,我已经有了一个获取 id 数组的方法,我尝试用 lambda 创建一个过滤列表,我的问题是,除了过滤列表之外,我是否只能在列表中保留必要的属性作为示例

example:例子:

 ages = [{'employedId': 1, 'age': 22},
         {'employedId': 2, 'age': 32},
         {'employedId': 3, 'age': 17},
         {'employedId': 4, 'age': 53},
         {'employedId': 5, 'age': 32},
         {'employedId': 6, 'age': 22}
         ]
list_filtred = list(filter(lambda tag: tag['age'] == 22, ages))

python output蟒蛇输出

[{'employedId': 1, 'age': 22}, 
 {'employedId': 6, 'age': 22}]

Can I create a lambda filtering method to have such an output or do I have to work on the array to create a new values ​​list?我可以创建一个 lambda 过滤方法来获得这样的输出还是我必须在数组上工作才能创建一个新的值列表?

expected output预期产出

[1,6]

You can use a list comprehension to access the value corresponding to the 'employedId' key after you've used the 'age' for filtering.在使用'age'进行过滤后,您可以使用列表推导式访问与'employedId'键对应的值。

>>> [tag['employedId'] for tag in ages if tag['age'] == 22]
[1, 6]

The filter function on its own won't do this, but you can do this using a functional, declarative style (rather than imperative). filter函数本身不会这样做,但您可以使用函数式声明式样式(而不是命令式)来执行此操作。

For example, to extract all the people whose age is 22例如,要提取所有年龄为 22 岁的人

list_filtered = list(filter(lambda tag: tag['age']==22, ages))

Lambda functions are powerful tools; Lambda 函数是强大的工具; you can construct a variety of conditions.您可以构建各种条件。

To get the array in the format you want, try the map function which uses similar principles but instead of filtering an array it applies the result of the function to each item in the array.要以您想要的格式获取数组,请尝试使用类似原理的map函数,但它不是过滤数组,而是将函数的结果应用于数组中的每个项目。

list_filtered = list(map(lambda x: x['employedId'], ages))

As an alternative leveraging your existing list statement, you could add a map statement that grabs the employedId key:作为替代利用现有的list语句,您可以添加一个map ,抓住声明employedId关键:

from operator import itemgetter

list(map(itemgetter('employedId'), filter(lambda tag: tag['age'] == 22, ages)))
[1, 6]

Otherwise, I think @CoryKramer's answer is a bit more readable否则,我认为@CoryKramer 的答案更具可读性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM