我知道这将会是一件非常简单的事情,但它只是对我而言不起作用。在字符串中查找数组中任何值的出现并将其打印出来
INDICATORS = ['dog', 'cat', 'bird']
STRING_1 = 'There was a tree with a bird in it'
STRING_2 = 'The dog was eating a bone'
STRING_3 = "Rick didn't let morty have a cat"
def FindIndicators(TEXT):
if any(x in TEXT for x in INDICATORS):
print x # 'x' being what I hoped was whatever the match would be (dog, cat)
预期输出:
FindIndicators(STRING_1)
# bird
FindIndicators(STRING_2)
# dog
FindIndicators(STRING_3)
# cat
相反,我得到了 'X' 的未解参考。我有一种感觉,一旦我看到答案,我就会面对办公桌。
'x'的作用域只存在于列表理解中。你必须从迭代器中实际检索一个值才能使用它。我推荐内置的[下一个](https://docs.python.org/3.6/library/functions.html#next) – Hamms