Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

enter image description here

like image 364
Stephen Avatar asked Aug 11 '17 11:08

Stephen


People also ask

How do you find the index of list elements that meet a condition in Python?

In Python to find a position of an element in a list using the index() method and it will search an element in the given list and return its index.

How do you find the index of a list using an element?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.


1 Answers

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
>>> 
like image 160
Christian Dean Avatar answered Oct 16 '22 03:10

Christian Dean