Here's the functionality I mean, and I do it pretty frequently so maybe I'm just reimplementing a built-in 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 let me do this with built-ins?
You essentially want to map example.get
on the sequence, and get the first true-ish value. For that, you can use filter
with the default filter function that does exactly that, and get the first of that using 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 isn’t iterated. In Python 2, you can use itertools
to get the lazy versions of the builtins, imap
and ifilter
you can use next()
builtin and generator expression:
next(example[key]
for key in ['dolphin', 'guide', 'answer', 'panic', 'bring']
if key in example)
if you want to use predefined function, it might be better to use filter, which accepts function as the first argument (lambda in example):
next(itertools.ifilter(lambda txt: 'a' in txt, ['foo', 'bar']))
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