我知道这将是一件非常简单的事情,但这对我不起作用。

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”的未解决参考。我有一种感觉,我一看到答案就马上要面对办公桌。

最佳答案

您误解了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

10-08 06:49