zoukankan      html  css  js  c++  java
  • 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']




  • 相关阅读:
    LeetCode#34 Search for a Range
    Multiplication algorithm
    LeetCode#31 Next Permutation
    Spring boot之Hello World
    spring boot 简介
    分布式-网络通信-线程
    分布式-网络通信-协议
    分布式-架构图
    9.leetcode70-climbing stairs
    8.Leetcode69 Sqrt(x) 笔记
  • 原文地址:https://www.cnblogs.com/Summer-skr--blog/p/14821813.html
Copyright © 2011-2022 走看看