Is there a built in function in Python that will return a single result given a list and a validation function?
For example I know I can do the following:
resource = list(filter(lambda x: x.uri == uri, subject.resources))[0]
The above will extract a resource from a list of resources, based on ther resource.uri field. Although this field value is uinique, so I know that I will either have 1 or 0 results. filter
function will iterate the whole list. In my case its 20 elements, but I want to know if there is some other built-in way to stop the iteration on first match.
Filter() is a built-in function in Python. The filter function can be applied to an iterable such as a list or a dictionary and create a new iterator. This new iterator can filter out certain specific elements based on the condition that you provide very efficiently.
the reason why it returns < filter object > is that, filter is class instead of built-in function.
In Python 2, filter() returns an actual list (which is not the efficient way to handle large data), so you don't need to wrap filter() in a list() call. Here are some other examples. Try it out: # lambda is used in place of a function print(filter(lambda x: x % 2 !=
See https://docs.python.org/3/library/functions.html#next
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
e.g. in your case:
resource = next(filter(lambda x: x.uri == uri, subject.resources), None)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With