【问题标题】:Shorter way of if statements in python [duplicate]python中if语句的较短方式[重复]
【发布时间】:2017-01-17 22:05:45
【问题描述】:
l = ["a", "b", "c", "d", "e"]
if "a" in l and "b" in l and "c" in l and "d" in l:
   pass

写这个 if 语句的更短的方式是什么?

试过了:

if ("a" and "b" and "c" and "d") in l:
    pass

但这似乎是不正确的。正确的方法是什么? Python 3

【问题讨论】:

  • 听说过allany
  • 请注意,第二个 sn-p 的计算结果为 if "a" in l:

标签: python if-statement


【解决方案1】:

一个想法可能是使用all(..) 和一个生成器:

if all(x in l for x in ['a','b','c','d']):
    pass

All 将任何类型的可迭代对象作为输入,并检查可迭代对象发出的所有元素,bool(..)True

现在在all 中,我们使用生成器。生成器的工作方式如下:

<expr> for <var> in <other-iterable>

(不带大括号)

因此,它获取&lt;other-iterable&gt; 中的每个元素并在其上调用&lt;expr&gt;。在这种情况下,&lt;expr&gt;x in lx&lt;var&gt;

#         <var>
#           |
 x in l for x in ['a','b','c','d']
#\----/          \---------------/
#<expr>           <other-iterable>

进一步解释generators

【讨论】:

  • 解释得很清楚
  • @MoinuddinQuadri:感谢您的友好评论:)。
【解决方案2】:

你可以使用集合:

l = { 'a', 'b', 'c', 'd', 'e' }

if { 'a', 'b', 'c', 'd' } <= l:
    pass

【讨论】:

    【解决方案3】:
    l = "abcde"
    if all(c in l for c in "abcd"):
        pass
    

    【讨论】:

    • 我认为 OP 在这里给出了一个带有单字符字符串的示例,显然在现实生活中可能会检查多字符字符串,但还是很好的答案。
    【解决方案4】:

    另一种方法是使用集合:

    l = ['a', 'b', 'c', 'd', 'e']
    if set(['a', 'b', 'c', 'd']).issubset(set(l)):
      pass
    

    【讨论】:

      【解决方案5】:

      对于这种情况,您也可以使用set 对象:

      l = ["a", "b", "c", "d", "e"]
      if  set(l) >= set(("a", "b", "c", "d")):
          print('pass')
      

      设置 >= 其他

      测试 other 中的每个元素是否都在集合中。

      https://docs.python.org/3/library/stdtypes.html?highlight=set#set.issuperset

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-06
        • 1970-01-01
        • 2016-08-03
        • 2016-03-26
        • 1970-01-01
        • 1970-01-01
        • 2010-12-31
        • 1970-01-01
        相关资源
        最近更新 更多