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

时间:2018-10-11 17:03:41

标签: python string python-3.x list if-statement

我有一个句子列表(exg)和一个水果名称列表(fruit_list)。我有一个代码来检查句子是否包含来自fruit_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,

但是我很想打印出哪个单词是fruit_list的一个元素,并且可以在句子中找到。在此示例中,我希望输出单词“苹果”,而不是句子中包含单词苹果。

希望这是有道理的。请发送帮助,非常感谢!

3 个答案:

答案 0 :(得分:3)

尝试使用epoch: #1 0 minutes between epoch epoch: #2 3 minutes between epoch epoch: #3 3 minutes between epoch epoch: #4 12 minutes between epoch epoch: #5 检查in,然后以后可以将word in fruit_list用作变量。

为了隔离找到哪个单词,您需要使用与fruit不同的方法。 any()仅关心是否可以在any()中找到word。并不关心哪个fruit_list或在列表中的哪个位置。

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)

答案 1 :(得分:1)

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

break

结果:

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,

答案 2 :(得分:-2)

这将完成工作。

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