Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the python equivalent of JavaScript's Array.prototype.find?

Tags:

python

find

I'm looking for something like: find(pred, iter) in python

obj = { 
         "foo_list": [ 
           {"name": "aaaa", "id": 111},
           {"name": "bbbb", "id": 222},
           {"name": "cccc", "id": 333}
         ]
}

How to: find(lambda x: x.get("name") == "bbbb", obj.get("foo_list", []))

like image 629
Benny Avatar asked Jul 04 '18 18:07

Benny


People also ask

How do I find an element in an array Python?

Python has a method to search for an element in an array, known as index(). If you would run x. index('p') you would get zero as output (first index).

What does array [:] do in Python?

basically used in array for slicing , understand bracket accept variable that mean value or key to display, and " : " is used to limit or slice the entire array into packets .

What is the prototype of array?

The JavaScript array prototype constructor is used to allow to add new methods and properties to the Array() object. If the method is constructed, then it will available for every array. When constructing a property, All arrays will be given the property, and its value, as default.

Can I use array prototype at ()?

Array.prototype.at()The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.


1 Answers

def find(pred, iterable):
  for element in iterable:
      if pred(element):
          return element
  return None

# usage:
find(lambda x: x.get("name") == "bbbb", obj.get("foo_list", []))
like image 117
Benny Avatar answered Oct 06 '22 04:10

Benny