Python教程:通过all

Python教程:通过all,第1张

之前通过比较的笨的方法,判断列表(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、判断列表中的每个字符串元素是否含另一个列表的所有字符串元素中
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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']

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/904508.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-15
下一篇 2022-05-15

发表评论

登录后才能评论

评论列表(0条)

保存