2016-11-15 36 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 
相关问题