简体   繁体   English

元素如果elif函数在python中使用数组

[英]Elementwise if elif function in python using arrays

I have a definition 我有一个定义

def myfunc(a, b):
    if a < (b*10):
        result = a*2
    else:
        result = a*(-1)
    return result

Now this obviously works perfectly when I feed in my a and b values one by one using for loops, however it takes forever (I've simplified the definition a wee bit) and I know from experience that passing in the values as an array will speed it up. 现在,当我使用for循环逐个输入我的ab值时,这显然是完美的,但是它需要永远(我已经将定义简化了一点)并且我从经验中知道将值作为数组传递将加快速度。

So how do I modify this code to accept arrays. 那么如何修改此代码以接受数组。 I've used the any() and all() commands but I must be using them wrong as my function only spits out one value rather than an array of values. 我已经使用了any()all()命令,但我必须使用它们,因为我的函数只吐出一个值而不是一个值数组。

An example of my desired output would be: 我想要的输出的一个例子是:

>>>a = np.array([1,5,50,500])
>>>b = 1
>>>print myfunc(a, b)
array([-1, -5, 100, 1000])

You could use np.where : 你可以使用np.where

def myfunc(a, b):
    return np.where(a < b*10, a*2, -a)    

For example, 例如,

In [48]: a = np.array([1, 5, 50, 500])

In [49]: b = 1

In [50]: myfunc(a, b)
Out[50]: array([   2,   10,  -50, -500])

Note the output is not the same as your desired output, but is consistent with the code you posted. 请注意,输出与所需输出不同,但与您发布的代码一致。 You can of course get the desired output by reversing the inequality: 你当然可以通过扭转不平等来获得所需的输出:

def myfunc(a, b):
    return np.where(a > b*10, a*2, -a)

then 然后

In [52]: myfunc(a, b)
Out[52]: array([  -1,   -5,  100, 1000])

Use a list comprehension: 使用列表理解:

myarray = [1, 5, 50, 500]
b = 1
[myfunc(a, b) for a in myarray]

Your function is simple enough that it can be dropped entirely: 你的功能很简单,可以完全删除:

arr = [1, 5, 50, 500]
arr = [a * 2 if a < b * 10 else -a for a in arr]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM