how can I make a numpy function that accepts a numpy array, an iterable, or a scalar?

前端 未结 4 1034
死守一世寂寞
死守一世寂寞 2021-02-19 20:50

Suppose I have this:

def incrementElements(x):
   return x+1

but I want to modify it so that it can take either a numpy array, an iterable, or

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-19 21:51

    Existing solutions all work. Here's yet another option.

    def incrementElements(x):
        try:
            iter(x)
        except TypeError:
            x = [x]
        x = np.array(x)
        # code that operators on x
    

提交回复
热议问题