How to get the index of filtered item in list using lambda?

一笑奈何 提交于 2020-08-27 22:29:03

问题


I have a list of fruits [{'name': 'apple', 'qty': 233}, {'name': 'orange', 'qty': '441'}]

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 ?


回答1:


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'})]

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
>>> 


来源:https://stackoverflow.com/questions/45634062/how-to-get-the-index-of-filtered-item-in-list-using-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!