【问题标题】:Python: One line for loop conditionPython:循环条件的一行
【发布时间】:2019-01-31 07:14:21
【问题描述】:

在下面的示例中,我正在测试是否在字符串 'hello' 中找到变量 'characters' 中的任何字符。

characters = ['a','b','c','d']

if True in [c in 'hello' for c in characters]: print('true')
else: print('false')

单行 for 循环创建一个布尔值列表。我想知道是否有任何方法不创建列表,而是在循环中的一个条件通过后传递整个条件。

【问题讨论】:

    标签: python python-3.x loops syntax


    【解决方案1】:

    通过在之前声明列表来试试这个。

    characters = ['a','b','c','d']
        a = []
        if True in a = [c in 'hello' for c in characters]: print('true')
        else: print('false')
    

    【讨论】:

      【解决方案2】:

      您可以使用set 的交集来获取两个文本的相交字符。如果你有,它们就在里面,如果 intersect-set 是空的,那么它们就在里面:

      characters = set("abcd")  # create a set of the chars you look for
      text = "hello"
      charInText = characters & set(text) # any element in both sets? (intersection)
      print ( 'true' if charInText != set() else 'false')  # intersection empty?
      
      text = "apple"
      charInText = characters & set(text) 
      print ( 'true' if charInText != set() else 'false') 
      

      输出:

      false #abcd + 你好 true #abcd + 苹果

      【讨论】:

        【解决方案3】:

        是的,您可以为此使用内置函数any

        if any(c in 'hello' for c in characters): print('true')
        

        【讨论】:

          【解决方案4】:

          您可以将any 与生成器表达式一起使用。这将一次从生成器中获取一个值,直到生成器耗尽或其中一个值是真实的。

          生成器表达式只会根据需要计算值,而不是像列表推导式那样一次性计算。

          if any(c in 'hello' for c in characters):
              ...
          

          【讨论】:

            猜你喜欢
            • 2021-03-19
            • 1970-01-01
            • 2020-04-05
            • 2017-07-11
            • 2019-06-04
            • 1970-01-01
            • 2020-06-22
            • 2011-05-18
            • 2021-05-29
            相关资源
            最近更新 更多