sub*_*ray 15 python for-loop if-statement list-comprehension
是否可以将此代码转换为列表理解?
for i in userInput:
if i in wordsTask:
a = i
break
Run Code Online (Sandbox Code Playgroud)
我知道如何转换它的一部分:
[i for i in userInput if i in wordsTask]
Run Code Online (Sandbox Code Playgroud)
但我不知道如何添加休息,文档也没有多大帮助.
任何帮助,将不胜感激.
Win*_*ert 42
a = next(i for i in userInput if i in wordsTask)
Run Code Online (Sandbox Code Playgroud)
要稍微分解一下:
[i for i in userInput if i in wordsTask]
Run Code Online (Sandbox Code Playgroud)
会产生一个清单.你想要的是列表中的第一项.一种方法是使用下一个功能:
next([i for i in userInput if i in wordsTask])
Run Code Online (Sandbox Code Playgroud)
Next从迭代器返回下一个项目.在像列表一样可迭代的情况下,它最终获取第一个项目.
但是没有理由实际构建列表,所以我们可以使用生成器表达式:
a = next(i for i in userInput if i in wordsTask)
Run Code Online (Sandbox Code Playgroud)
另请注意,如果生成器表达式为空,则会导致异常:StopIteration.您可能想要处理这种情况.或者您可以添加默认值
a = next((i for i in userInput if i in wordsTask), 42)
Run Code Online (Sandbox Code Playgroud)