我想从bananas-10提取thought1,从10-bananas提取thought2。我该怎么做?我很困惑,因为我不确定如何找出字符串中是否存在食物。

foods = ["bagels", "oranges", "bananas"]
thought1 = "I want some bananas-10"
thought2 = "I want some 10-bananas"
if any(food in thought1 for food in foods):
    # extractedfood = ???

最佳答案

我将使用以下列表理解方法:

text = thought1 + " " + thought2 # To handle both strings
result = [a for a in text.split() for b in foods if b in a]

print result


输出:

['bananas-10', '10-bananas']

08-25 05:12