字符串包含列表的所有元素 [英] String contains all the elements of a list
本文介绍了字符串包含列表的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在转向Python,但对于pythonic方法来说还是一个相对较新的事物.我想编写一个函数,该函数接受一个字符串和一个列表,如果列表中的所有元素都出现在字符串中,则返回true.
I am shifting to Python, and am still relatively new to the pythonic approach. I want to write a function that takes a string and a list and returns true if all the elements in the list occur in the string.
这似乎很简单.但是,我面临一些困难.代码是这样的:
This seemed fairly simple. However, I am facing some difficulties with it. The code goes something like this:
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
此外,我希望有人可以在这里建议一种可能的正则表达式方法.我也在尝试用手.
Also, I was hoping if someone could suggest a possible regex approach here. I am trying out my hands on them too.
推荐答案
>>> all(x in 'tomato' for x in ['t','o','m','a'])
True
>>> all(x in 'potato' for x in ['t','o','m','a'])
False
这篇关于字符串包含列表的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文