2016-11-15 79 views
1

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

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' 的未解參考。我有一種感覺,一旦我看到答案,我就會面對辦公桌。

+1

'x'的作用域只存在於列表理解中。你必須從迭代器中實際檢索一個值才能使用它。我推薦內置的[下一個](https://docs.python.org/3.6/library/functions.html#next) – Hamms

回答

3

你誤解如何any()作品。它消耗你所給的任何東西,並返回True或False。之後不存在x

>>> INDICATORS = ['dog', 'cat', 'bird'] 
>>> TEXT = 'There was a tree with a bird in it' 
>>> [x in TEXT for x in INDICATORS] 
[False, False, True] 
>>> any(x in TEXT for x in INDICATORS) 
True 

而是做到這一點:

>>> for x in INDICATORS: 
...  if x in TEXT: 
...   print x 
... 
bird 
+0

非常感謝,這使得更多的意義。 –

+0

請記住,如果TEXT中的x匹配子字符串,那麼cat將匹配'category'和'scattered'。您可能想要使用@prune使用的測試:'如果TEXT.split()中的x'表示TEXT中整個單詞中的'x'。 – Harvey

2

如文檔中所描述的,任何返回一個布爾值,不匹配的列表。所有呼叫所做的就是表明至少存在一個「命中」。

可變X只存在內的發電機表達;它在後面排隊,所以你不能打印它。

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): 
    # This isn't the most Pythonic way, 
    # but it's near to your original intent 
    hits = [x for x in TEXT.split() if x in INDICATORS] 
    for x in hits: 
     print x 

print FindIndicators(STRING_1) 
# bird 

print FindIndicators(STRING_2) 
# dog 

print FindIndicators(STRING_3) 
# cat 
相關問題