Python 通过all()判断列表(list)中所有元素是否都包含某个字符串(string)

 

之前通过比较的笨的方法,判断列表(list)中所有元素是否包含在字符串(string)中,后来发现可以用all()来判断,查找了一些资料,写出来发现很简单,下面分享一下代码。

 

1、判断列表(list)中,所有元素是否在集合(set)中

list_string = ['big', 'letters']
string_set = set(['hello', 'hi', 'big', 'cccc', 'letters', 'anotherword'])
result
= all([word in string_set for word in list_string]) #结果是True 

 

2、判断列表中的每个字符串元素是否含另一个列表的所有字符串元素中

list_string= ['big', 'letters']
list_text = ['hello letters', 'big hi letters', 'big superman letters']
result = all([word in text for word in list_string for text in list_text]) 
#结果是False,因为'big'不在'hello letters'中。

 

3、如果要获取符合条件字符串,可以用 filter

list_string= ['big', 'letters']
list_text = ['hello letters', 'big hi letters', 'big superman letters']
all_words = list(filter(lambda text: all([word in text for word in list_string]), list_text ))
print(all_words) 
#['big hi letters', 'big superman letters']

 





posted @ 2021-05-28 13:34  PythonGirl  阅读(2987)  评论(0编辑  收藏  举报