Is there a built-in Python function that will return the first True-ish value when matching functions over iterable?

Here, I mean functionality, and I do it quite often, so maybe I'm just redefining the built-in module that I haven't seen:

import itertools def first(fn, *args): for x in itertools.chain(*args): value = fn(x) if value: return value # Example use: example = {'answer': 42, 'bring': 'towel'} print first(example.get, ['dolphin', 'guide', 'answer', 'panic', 'bring']) # Prints 42 

Does Python allow this with built-in modules?

+6
source share
3 answers

You really want to display example.get in sequence and get the first true value. To do this, you can use filter with a default filter function that does just that, and get the first one with next :

 >>> example = {'answer': 42, 'bring': 'towel'} >>> lst = ['dolphin', 'guide', 'answer', 'panic', 'bring'] >>> next(filter(None, map(example.get, lst))) 42 

In Python 3, all these things are lazy, so the whole sequence is not repeated. In Python 2, you can use itertools to get lazy versions of the built-in functions, imap and ifilter

+3
source

you can use the expression next() builtin and generator:

 next(example[key] for key in ['dolphin', 'guide', 'answer', 'panic', 'bring'] if key in example) 

if you want to use a predefined function, it is better to use a filter that takes the function as the first argument (lambda in the example):

 next(itertools.ifilter(lambda txt: 'a' in txt, ['foo', 'bar'])) 
+2
source

I don’t think there is a built-in function to do what you want. There is probably a more pythonic way of doing what you do:

 example = {'answer': 42, 'bring': 'towel'} keys = ['dolphin', 'guide', 'answer', 'panic', 'bring'] print filter(lambda x: x, map(example.get, keys))[0] 

The disadvantage of this method is that it will iterate over the entire list, and not exit the first value. You should also add additional checks to make sure the list is not empty.

0
source

Source: https://habr.com/ru/post/987513/


All Articles