Python idiom to return first item or None

后端 未结 24 2055
清酒与你
清酒与你 2020-12-07 07:46

I\'m sure there\'s a simpler way of doing this that\'s just not occurring to me.

I\'m calling a bunch of methods that return a list. The list may be empty. If the

24条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 08:12

    Regarding idioms, there is an itertools recipe called nth.

    From itertools recipes:

    def nth(iterable, n, default=None):
        "Returns the nth item or a default value"
        return next(islice(iterable, n, None), default)
    

    If you want one-liners, consider installing a library that implements this recipe for you, e.g. more_itertools:

    import more_itertools as mit
    
    mit.nth([3, 2, 1], 0)
    # 3
    
    mit.nth([], 0)                                             # default is `None`
    # None
    

    Another tool is available that only returns the first item, called more_itertools.first.

    mit.first([3, 2, 1])
    # 3
    
    mit.first([], default=None)
    # None
    

    These itertools scale generically for any iterable, not only for lists.

提交回复
热议问题