【问题标题】:Python 3 if not condition simplificationPython 3 if not 条件简化
【发布时间】:2017-06-23 17:22:37
【问题描述】:

这两个条件检查是否相同?我想不出如何检查它们是否相同

l1 = []
l2 = []

if not l1 and not l2:
    print ('y')

if not (l1 and l2):
    print ('y')

感谢所有回复的人,我已经做了一些基本的计时,看看哪个更快

import time
l1 = []
l2 = []

st = time.time()
for i in range(100000000):
    if not l1 and not l2:
        pass
end = time.time()
print ('if not l1 and not l2: '+str(end-st))

st = time.time()
for i in range(100000000):
    if not (l1 or l2):
        pass
end = time.time()
print ('if not (l1 or l2): '+str(end-st))

打印:

if not l1 and not l2: 8.533874750137329
if not (l1 or l2): 7.91820216178894

【问题讨论】:

    标签: python python-3.x if-statement


    【解决方案1】:

    不,它们不一样。见De Morgan's laws

    一个反例是:

    l1 = [0]
    l2 = []
    

    【讨论】:

      【解决方案2】:

      它们不一样。您需要按如下方式修改第二个条件,使它们等效:

      l1 = []
      l2 = []
      
      if not l1 and not l2:
          print ('y')
      
      if not (l1 or l2):
          print ('y')
      

      【讨论】:

        【解决方案3】:

        如果你想一样,使用或操作:

        l1 = []
        l2 = []
        
        if not l1 and not l2:
            print ('y')
        

        等效:

        if not (l1 or l2):
            print ('y')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-12
          • 2016-09-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多