我想检查多个字符串是否在一个较大的字符串中,称为"str_a"。以下是我目前拥有的,它的工作原理。
animals = {"giraffe", "tiger"}
str_a = "A giraffe is taller than a tiger."
if "giraffe" in str_a or "tiger" in f:
print ("T")
else:
print ("F")
但是,我想以更简洁的方式代表if-statement,我觉得set.Intersection可以帮助我实现这一目标。我用set.Intersection尝试了以下内容,它打印出"F"而不是“T" - I'm不确定为什么。任何对此的指导都会受到赞赏!
animals = {"giraffe", "tiger"}
str_a = "A giraffe is taller than a tiger."
matches = animals.intersection(str_a)
if matches:
print ("T")
else:
print ("F")
分析解答
你应该使用any
:
if any(animal in str_a for animal in animals):
print('T')
else:
print('F'