检查列表中的所有数字在Python中是否都使用相同的符号? [英] Check if all numbers in a list are same sign in Python?

查看:184
本文介绍了检查列表中的所有数字在Python中是否都使用相同的符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何判断一个数字列表(或可迭代数字)是否都具有相同的符号?

How can I tell if a list (or iterable) of numbers all have the same sign?

这是我的第一个(天真)草稿:

Here's my first (naive) draft:

def all_same_sign(list):

    negative_count = 0

    for x in list:
        if x < 0:
            negative_count += 1

    return negative_count == 0 or negative_count == len(list)

是否有更Python化和/或正确的方法来做到这一点?首先想到的是一旦出现相反的迹象,就停止迭代.

Is there a more pythonic and/or correct way of doing this? First thing that comes to mind is to stop iterating once you have opposite signs.

更新

尽管我对性能感到好奇,但到目前为止,我还是喜欢答案.我不是表演迷,但我认为在处理列表时,考虑表演是合理的.对于我的特定用例,我认为这没什么大不了的,但是对于这个问题的完整性,我认为解决这个问题很好.我的理解是最小和最大函数具有O(n)性能.到目前为止,两个建议的答案具有O(2n)性能,而我上面的例程(一旦检测到相反的符号,则添加短路退出)将具有最差的O(n)性能.有想法吗?

I like the answers so far although I wonder about performance. I'm not a performance junkie but I think when dealing with lists it's reasonable to consider the performance. For my particular use-case I don't think it will be a big deal but for completeness of this question I think it's good to address it. My understanding is the min and max functions have O(n) performance. The two suggested answers so far have O(2n) performance whereas my above routine adding a short circuit to quit once an opposite sign is detected will have at worst O(n) performance. Thoughts?

推荐答案

您可以使用all函数:-

>>> x = [1, 2, 3, 4, 5]

>>> all(item >= 0 for item in x) or all(item < 0 for item in x)
True

不知道这是否是最Python化的方式.

Don't know whether it's the most pythonic way.

这篇关于检查列表中的所有数字在Python中是否都使用相同的符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆