字符串包含列表的所有元素
问题内容:
我正在转向Python,但对于pythonic方法还是相对较新的。我想编写一个接受字符串和列表的函数,如果列表中的所有元素都出现在字符串中,则返回true。
这似乎很简单。但是,我面临一些困难。该代码是这样的:
def myfun(str,list):
for a in list:
if not a in str:
return False
return True
Example : myfun('tomato',['t','o','m','a']) should return true
myfun('potato',['t','o','m','a']) should return false
myfun('tomato',['t','o','m']) should return true
另外,我希望有人可以在这里建议一种可能的正则表达式方法。我也在尝试用它们。
问题答案:
>>> all(x in 'tomato' for x in ['t','o','m','a'])
True
>>> all(x in 'potato' for x in ['t','o','m','a'])
False