Creating a Python list comprehension with an if and break

后端 未结 1 1900
悲&欢浪女
悲&欢浪女 2020-12-09 04:05

Is it possible to turn this code into a list comprehension?

for i in userInput:
    if i in wordsTask:
        a = i
        break

I know h

相关标签:
1条回答
  • 2020-12-09 04:44
    a = next(i for i in userInput if i in wordsTask)
    

    To break it down somewhat:

    [i for i in userInput if i in wordsTask]
    

    Will produce a list. What you want is the first item in the list. One way to do this is with the next function:

    next([i for i in userInput if i in wordsTask])
    

    Next returns the next item from an iterator. In the case of iterable like a list, it ends up taking the first item.

    But there is no reason to actually build the list, so we can use a generator expression instead:

    a = next(i for i in userInput if i in wordsTask)
    

    Also, note that if the generator expression is empty, this will result in an exception: StopIteration. You may want to handle that situation. Or you can add a default

    a = next((i for i in userInput if i in wordsTask), 42)
    
    0 讨论(0)
提交回复
热议问题