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

后端 未结 3 1860
傲寒
傲寒 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:01

    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

    0 讨论(0)
  • 2021-01-12 18:05

    I don't think there's a built in function to do what you want. There is an arguably more Pythonic way of doing what you're doing:

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

    The downside of this method is that it will iterate through the whole list, instead of breaking out at the first value. You also have to add extra checks to make sure the list isn't empty.

    0 讨论(0)
  • 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']))
    
    0 讨论(0)
提交回复
热议问题