我有一个句子列表(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的句子。你知道吗
希望这有意义。请给我帮助,非常感谢!你知道吗
这就行了。你知道吗
尝试使用
in
来检查word in fruit_list
,然后您可以稍后使用fruit
作为变量。你知道吗为了找出找到的单词,您需要使用不同于
any()
的方法。any()
它只关心是否能在fruit_list
中找到word
。它不关心在列表中的哪个word
或在哪里找到它。你知道吗结果:
您可以将
for
子句与break
一起使用,而不是将any
与生成器表达式一起使用:结果:
更惯用的方法是迭代列表而不是索引范围:
相关问题 更多 >
编程相关推荐