[英]Find occurences of any value in an array in a string and print it
I know this ones going to be something super simple, but it's just not working for me. 我知道这将是一件非常简单的事情,但这对我不起作用。
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)
Expected output: 预期产量:
FindIndicators(STRING_1)
# bird
FindIndicators(STRING_2)
# dog
FindIndicators(STRING_3)
# cat
Instead I'm getting an unsolved reference for 'x'. 相反,我得到了“ x”的未解决参考。 I have a feeling I'm going to face desk as soon as I see an answer.
我有一种感觉,我一看到答案就马上要面对办公桌。
You're misunderstanding how any()
works. 您误解了
any()
工作原理。 It consumes whatever you give it and returns True or False. 它消耗您提供的任何内容,并返回True或False。
x
doesn't exist after. 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
Instead do this: 而是这样做:
>>> for x in INDICATORS:
... if x in TEXT:
... print x
...
bird
As described in the documentation, any returns a Boolean value, not a list of matches. 如文档中所述, any返回一个布尔值,而不是匹配列表。 All that call does is to indicate the presence of at least one "hit".
该调用所做的只是指示至少一个“命中”的存在。
The variable x exists only within the generator expression; 变量x仅存在于生成器表达式中; it's gone in the line after, so you can't print it.
它已经排在后面了,所以您不能打印它。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.