首页 > 编程语言 > 详细

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

时间:2021-05-28 14:30:07      阅读:20      评论:0      收藏:0      [点我收藏+]

 

之前通过比较的笨的方法,判断列表(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‘]

 





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

原文:https://www.cnblogs.com/Summer-skr--blog/p/14821813.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!