之前通過比較的笨的方法,判斷列表(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']
