Python idiom to return first item or None

后端 未结 24 1986
清酒与你
清酒与你 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

    If you find yourself trying to pluck the first thing (or None) from a list comprehension you can switch to a generator to do it like:

    next((x for x in blah if cond), None)
    

    Pro: works if blah isn't indexable Con: it's unfamiliar syntax. It's useful while hacking around and filtering stuff in ipython though.

提交回复
热议问题