查找列表是否有负号

2024-06-26 02:06:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数。在这个函数中,我传递了一个列表。你知道吗

l = [1, 2, 3]

现在我想写两个条件,l通过或-l通过。-l表示否定列表中的所有值。
例如

-l = [ -1, -2, -3]

因此,在函数中,l或-l将作为参数传递。你知道吗

fun test(l):
    Condition1:
        # do if list is negative
    Condition 2:
        # do if list isbpositive

如何检查函数参数列表中的负号?或者有什么方法可以解决这个问题?你知道吗


Tags: 函数test列表ifis函数参数condition条件
3条回答

我觉得不可能,因为你打电话来的时候

test(-l)

-l求值,然后传递给函数。相反,你可以这样做:

def test(l, negative = False):
    if (negative == True):
        l = -l
        ...
    else:            
        ...

并称之为:

test(l, True) # to pass it as negative

虽然我可能误解了这个问题,你可以用这样的话

>>> def is_neg(l):
...    # ascertain the sign of the values
...    l = map(lambda value: value < 0, l)
...    # ascertain that all values are negative
...    return all(l)
>>>
>>> l = [-1, -2, -3]
>>> print(is_neg(l))
True
>>> l = [-1, 2, -3]
>>> print(is_neg(l))
False

好吧,据我所知,列表上没有一元减号运算符-你必须自己创建它。你知道吗

上面说。。。不变量是l中的所有元素都是正的还是负的?如果是这样,检查第一个条目就足够了:

def test(l):
    if l[0] > 0:
        # Do if list is positive
    else:
        # Do if list is negative

但这似乎不是一个明确的问题。。例如,您如何处理列表中的0?这合法吗?你知道吗

如果你允许混合,那么我无法知道[-1, 2, -3]是原始列表,还是有人倒了[1, -2, 3],因为结果是一样的-在这种情况下,阳性/阴性测试是没有意义的。你知道吗

如果你实现了你自己的一元减号操作符,在你自己的列表对象中,你可以自己跟踪它。你知道吗

相关问题 更多 >