Shortcut OR-chain applied on list

后端 未结 2 1979
名媛妹妹
名媛妹妹 2020-12-12 05:34

I\'d like to do something like this:

x = f(a[0]) or f(a[1]) or f(a[2]) or f(a[3]) or …

with a given list a and a given functio

相关标签:
2条回答
  • 2020-12-12 05:50

    I'm now using this:

    x = next((v for v in (f(x) for x in a) if v), False)
    

    It's a working idiom without doubling the call of f and without introducing a hacky local, but it still is not very readable (especially if x, f, a, and v are longer than one letter).

    I'd be happy to hear of a better solution.

    0 讨论(0)
  • 2020-12-12 05:58

    This should work:

    next((x for y in a for x in (f(y),) if x),False)
    
    0 讨论(0)
提交回复
热议问题