Is there a built-in Python function which will return the first True-ish value when mapping a function over an iterable?

后端 未结 3 1892
傲寒
傲寒 2021-01-12 17:39

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         


        
3条回答
  •  盖世英雄少女心
    2021-01-12 18:17

    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']))
    

提交回复
热议问题