Python:在 any() 函数中扩展迭代器变量的范围 [英] Python: Expanding the scope of the iterator variable in the any() function
本文介绍了Python:在 any() 函数中扩展迭代器变量的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一些结构上等效的现实世界代码,我预计 firstAdjective
的结果将是 quick
.但结果显示 word
超出范围.有什么巧妙的解决方案可以克服这个问题,但仍然保留我想做的语言"风格?
解决方案
您可以在生成器表达式上使用next
:
firstAdjective = next((如果单词在文本中,则在形容词中逐字逐句),无)if first形容词:...
当找不到单词时返回默认值 None
(credit @Bakuriu)
试用:
<预><代码>>>>firstadjective = next((如果单词在文本中,则形容词中的单词一个单词),无)>>>第一个形容词'快的'I wrote some structurally equivalent real world code, where I anticipated the result for firstAdjective
would be quick
. But the result shows that word
is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do?
>>> text = 'the quick brown fox jumps over the lazy dog'
>>> adjectives = ['slow', 'quick', 'brown', 'lazy']
>>> if any(word in text for word in adjectives):
... firstAdjective = word
...
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
NameError: name 'word' is not defined
解决方案
You can use next
on a generator expression:
firstAdjective = next((word for word in adjectives if word in text), None)
if firstAdjective:
...
A default value of None
is returned when the word is not found (credit @Bakuriu)
Trial:
>>> firstadjective = next((word for word in adjectives if word in text), None)
>>> firstadjective
'quick'
这篇关于Python:在 any() 函数中扩展迭代器变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文