Python:如何检查字符串是否包含列表中的元素并显示该元素?

2024-09-28 16:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个句子列表(exg)和一个水果名列表(fruit\u list)。我有一个代码来检查句子是否包含水果列表中的元素,如下所示:

exg = ["I love apple.", "there are lots of health benefits of apple.", 
       "apple is especially hight in Vitamin C,", "alos provide Vitamin A as a powerful antioxidant!"]


fruit_list = ["pear", "banana", "mongo", "blueberry", "kiwi", "apple", "orange"]

for j in range(0, len(exg)):
    sentence = exg[j]
    if any(word in sentence for word in fruit_list):
        print(sentence)

输出如下:只有句子包含“apple”的单词

I love apple.
there are lots of health benefits of apple.
apple is especially hight in Vitamin C,

但是我想打印出哪个单词是水果列表中的一个元素,哪个单词是在句子中找到的。在这个例子中,我希望输出一个单词“apple”,而不是包含单词apple的句子。你知道吗

希望这有意义。请给我帮助,非常感谢!你知道吗


Tags: ofin元素apple列表单词sentencelist
3条回答

这就行了。你知道吗

for j in range(0, len(fruit_list)):
fruit = fruit_list[j]
if any(fruit in sentence for sentence in exg):
    print(fruit)

尝试使用in来检查word in fruit_list,然后您可以稍后使用fruit作为变量。你知道吗

为了找出找到的单词,您需要使用不同于any()的方法。any()它只关心是否能在fruit_list中找到word。它不关心在列表中的哪个word或在哪里找到它。你知道吗

exg = ["I love apple.", "there are lots of health benefits of apple.", 
   "apple is especially hight in Vitamin C,", "alos provide Vitamin A as a powerful antioxidant!"]


fruit_list = ["pear", "banana", "mongo", "blueberry", "kiwi", "apple", "orange"]

# You can remove the 0 from range, because it starts at 0 by default
# You can also loop through sentence directly
for sentence in exg:
    for word in fruit_list:
        if(word in sentence):
            print("Found word:", word, "  in:", sentence)

结果:

Found word: apple  in: I love apple.
Found word: apple  in: there are lots of health benefits of apple.
Found word: apple  in: apple is especially hight in Vitamin C,

您可以将for子句与break一起使用,而不是将any与生成器表达式一起使用:

for j in range(0, len(exg)):
    sentence = exg[j]
    for word in fruit_list:
        if word in sentence:
            print(f'{word}: {sentence}')
            break

结果:

apple: I love apple.
apple: there are lots of health benefits of apple.
apple: apple is especially hight in Vitamin C,

更惯用的方法是迭代列表而不是索引范围:

for sentence in exg:
    for word in fruit_list:
        if word in sentence:
            print(f'{word}: {sentence}')
            break

相关问题 更多 >