【问题标题】:What is the best way to return a boolean when a negative value exists in a list?当列表中存在负值时返回布尔值的最佳方法是什么?
【发布时间】:2022-11-18 19:15:33
【问题描述】:

我有以下函数告诉我们 series 至少有一个负值:

def has_negative(series):
    v=False
    for i in range(len(series)):
        if series[i]<0:
            v=True
            break
    return v

当我们在一个例子中使用这个函数时,我们得到:

y=[1,2,3,4,5,6,7,8,9]
z=[1,-2,3,4,5,6,7,8,9]

print(has_negative(y))
print(has_negative(y))

输出:

>>> False
>>> True

该功能似乎运行良好,虽然我想缩短它,但如果您提出任何建议,我们将不胜感激

【问题讨论】:

  • @HampusLarsson 能否将您的评论转换为答案?

标签: python list function boolean


【解决方案1】:

您可以利用内置的任何功能如下:

def has_negative(lst):
    return any(e < 0 for e in lst)

print(has_negative([1,2,3,4,5,6,7,8,9]))
print(has_negative([1,-2,3,4,5,6,7,8,9]))

输出:

False
True

【讨论】:

    【解决方案2】:

    您可以对列表进行排序并获取第一个元素,检查它是否为负数。使用这种方法,您不必遍历数组:

    sorted(series)[0] < 0
    

    【讨论】:

      【解决方案3】:

      您可以进行多项改进:

      def has_negative(series):
          for i in series:
              if i < 0:
                  return True
          return False
      

      或者它可以像这样收缩成一行:

      print(bool([i for i in z if i<0]))
      

      【讨论】:

      • 你的第二个建议胜过我的回答(使用任何) 考虑到 OP 问题中的值列表,增加了约 30%。有了更长的列表,我的答案胜过你的。这是违反直觉的,因为在您的代码中,输入列表的每个元素都必须进行测试,并且必须构建一个列表。而对于我的解决方案任何功能可以(我不知道它是如何实现的)提前中断 - 即,一旦它观察到负值。知道为什么会这样吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      相关资源
      最近更新 更多