【问题标题】:Python: how to check if a string contains an element from a list and bring out that element?Python:如何检查字符串是否包含列表中的元素并带出该元素?
【发布时间】:2019-03-16 20:30:03
【问题描述】:

我有一个句子列表 (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 的一个元素并且在句子中找到。在此示例中,我希望输出单词“apple”,而不是包含单词 apple 的句子。

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

【问题讨论】:

  • 嗯,你知道你想要什么 - 你尝试过什么实现它?

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


【解决方案1】:

尝试使用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,

【讨论】:

    【解决方案2】:

    您可以将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
    

    【讨论】:

      【解决方案3】:

      这样就可以了。

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

      【讨论】:

        猜你喜欢
        • 2013-09-17
        • 2017-11-20
        • 2010-10-04
        • 2021-10-31
        • 1970-01-01
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多