Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找列表是否有负号_Python_Numpy - Fatal编程技术网

Python 查找列表是否有负号

Python 查找列表是否有负号,python,numpy,Python,Numpy,我有一个功能。在该函数中,我传递一个列表 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 如何检查函数参数中列表的负号?或者解决这个问题的

我有一个功能。在该函数中,我传递一个列表

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

如何检查函数参数中列表的负号?或者解决这个问题的方法是什么?

好吧,据我所知,列表中没有一元减号运算符-您必须自己创建它

也就是说。。。
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]
,因为结果是一样的-在这种情况下,阳性/阴性测试是没有意义的


不过,如果您在自己的类似列表的对象中实现自己的一元减号运算符,您可以自己跟踪它。

我认为这是不可能的,因为当您调用

test(-l)
计算
-l
,然后将其传递给函数。相反,您可以尝试以下方法:

def test(l, negative = False):
    if (negative == True):
        l = -l
        ...
    else:            
        ...
并称之为:

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

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

>>def为负(l):
...    # 确定值的符号
...    l=map(λ值:值<0,l)
...    # 确定所有值均为负值
...    全部返回(l)
>>>
>>>l=[-1,-2,-3]
>>>印刷品(正反面(l))
真的
>>>l=[-1,2,-3]
>>>印刷品(正反面(l))
假的

我想你可以利用全局范围。问题是,在本例中,您的全局范围中不应该已经有
-a
(例如,由
负a=-a
定义的
负a

但是如果你已经有了一个
减a
,你会把
减a
传递给你的
测试()
,而不是
测试(-a)
,对吗

>>> import numpy as np
>>> def test_sign(A):
    q=globals()
    q_arrays=[q[item] for item in q if isinstance(q[item], np.ndarray)]
    result=False
    for item in q_arrays:
        if np.all(item==-A):
            result=True
            break
    return result
>>> a=np.arange(10)
>>> test_sign(a)
False
>>> test_sign(-a)
True

在这个IPython序列中,我定义了一个自定义的求反函数,该函数设置一个标志。该标志可通过
*
和默认值选择性地传递给
测试

In [47]: ll = np.array([1,2,3])
In [61]: def makeneg(ll):
   ....:     return -ll,True
   ....: 

In [62]: makeneg(ll)
Out[62]: (array([-1, -2, -3]), True)

In [66]: def test(ll, flag=False):
    if flag:
        print ll, 'is negated'
    else:
        print ll,'is not negated'
   ....:         

In [67]: test(ll)
[1 2 3] is not negated

In [68]: test(*makeneg(ll))
[-1 -2 -3] is negated

关键字args是有问题的,但是在这种情况下我如何实现呢?嗯。。。我不知道numpy,但你可能需要与原始列表numpy进行比较。。。嗯,这使得我所说的大部分内容不一定适用,但既然它得到了升级,那么它一定是有用的…
np.negative([1,2,3])
产生
数组([-1,-2,-3])
,就像-
数组([1,2,3])
一样。这并不是说这有助于解决OP问题。