如何使用lambda获取列表中已过滤项目的索引? [英] How to get the index of filtered item in list using lambda?

查看:261
本文介绍了如何使用lambda获取列表中已过滤项目的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个水果清单 [{'name':'apple','qty':233},{'name':'orange','qty':'441'}]

当我使用lambda过滤橙色的列表时, list(filter(lambda x:x ['name'] =='orange',水果)),我得到了正确的字典,但无法获取字典的索引。索引应为1而不是0。

When i filter the list for orange using lambda, list(filter(lambda x: x['name']=='orange', fruits)) , i get the right dict but i can not get the index of the dict. Index should be 1 not 0.

我如何获取已过滤项目的正确索引?

How do i get the right index of the filtered item ?

< a href = https://i.stack.imgur.com/QnaoB.png rel = nofollow noreferrer>

推荐答案

您可以使用列表推导和 enumerate() 代替:

You can use a list comprehension and enumerate() instead:

>>> fruits = [{'name': 'apple', 'qty': 233}, {'name': 'orange', 'qty': '441'}]
>>> [(idx, fruit) for idx, fruit in enumerate(fruits) if fruit['name'] == 'orange']
[(1, {'name': 'orange', 'qty': '441'})]

就像@ChrisRands发表在评论中一样,您也可以使用通过为您的水果列表创建枚举对象来过滤

Like @ChrisRands posted in the comments, you could also use filter by creating a enumeration object for your fruits list:

>>> list(filter(lambda fruit: fruit[1]['name'] == 'orange', enumerate(fruits)))
[(1, {'name': 'orange', 'qty': '441'})]
>>> 

以下是两种方法的计时:

Here are some timings for the two methods:

>>> setup = \
      "fruits = [{'name': 'apple', 'qty': 233}, {'name': 'orange', 'qty': '441'}]"
>>> listcomp = \
     "[(idx, fruit) for idx, fruit in enumerate(fruits) if fruit['name'] == 'orange']"
>>> filter_lambda = \
     "list(filter(lambda fruit: fruit[1]['name'] == 'orange', enumerate(fruits)))"
>>> 
>>> timeit(setup=setup, stmt=listcomp)
1.0297133629997006
>>> timeit(setup=setup, stmt=filter_lambda)
1.6447856079998928
>>> 

这篇关于如何使用lambda获取列表中已过滤项目的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆