A memo that investigated how to perform operations like ʻArray.prototype.find ()` in JavaScript in Python.
javascript find()
const fruits = ["apple", "lemon", "melon", "orange"];
const elm = fruits.find(e => e.endsWith("n"));
console.log(elm); // "lemon"
The filter
function takes an anonymous function described by a lambda expression as the first argument and applies it to each element of the list of second arguments. The iterator is returned by extracting the elements for which the result is true, so the result can be obtained as a list by applying the list
function.
filter function
fruits = ["apple", "lemon", "melon", "orange"]
#filter function
lst = list(filter(lambda x: x.endswith("n"), fruits))
assert lst == ["lemon", "melon"]
#filter function No matching element
lst = list(filter(lambda x: x.endswith("x"), fruits))
assert lst == []
If you apply the next
function instead of the list
function, you will get the first element that matches the condition.
In the second argument of the filter
function, specify None
as the default value when the element is not found. (Note that without this specification, a StopIteration
exception will be thrown and the system will terminate abnormally.)
filter function+find with next function
#find by filter function
elm = next(filter(lambda x: x.endswith("n"), fruits), None)
assert elm == "lemon"
#find by filter function No matching element
elm = next(filter(lambda x: x.endswith("x"), fruits), None)
assert elm == None
A generator expression is an expression that defines a generator in a notation such as list comprehension. Since a generator returns an iterator, it can be passed to the next
function.
Generator type+find with next function
#Generator type find
elm = next((f for f in fruits if f.endswith("n")), None)
assert elm == "lemon"
#Find by generator expression No matching element
elm = next((f for f in fruits if f.endswith("x")), None)
assert elm == None
The first argument is a generator expression. The difference from the list comprehension is that it is enclosed in ()
instead of []
.
Generator type
(f for f in fruits if f.endswith("x"))
Recommended Posts