我知道這將會是一件非常簡單的事情,但它只是對我而言不起作用。在字符串中查找數組中任何值的出現並將其打印出來
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