Skip to main content
 首页 » 编程设计

python之在字符串中的数组中查找任何值的出现并打印它

2025年05月04日40Renyi-Fan

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

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”的未解决引用。我有一种感觉,我一看到答案就会去办公 table 。

请您参考如下方法:

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