查找字符串中数组中任何值的出现并打印出来

时间:2016-11-15 00:48:49

标签: python

我知道这些会变得非常简单,但它对我不起作用。

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'引用。我有一种感觉,一看到答案,我就会面对书桌。

2 个答案:

答案 0 :(得分:3)

您误解了HashMap的工作原理。它消耗你给它的任何东西并返回True或False。 any()之后不存在。

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

答案 1 :(得分: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