简体   繁体   English

以与内置数组兼容的方式扩展numpy数组

[英]Extend numpy array in a way compatible with builtin arrays

I am trying to write code that would not depend on whether the user uses np.array or a builtin array. 我正在尝试编写不依赖于用户使用np.array还是内置数组的代码。 I am trying to avoid checking object types, etc. The only problem that I have is in extending arrays. 我试图避免检查对象类型等。我唯一的问题是扩展数组。 For example, if I have two Python arrays, a and b , to extend the first by the second, I can either do a = a + b , or a.extend(b) . 例如,如果我有两个Python数组ab ,以将第一个数组扩展到第二个数组,则可以执行a = a + ba.extend(b) On the other hand, if a is a numpy array, I need to use np.append or something else. 另一方面,如果a是一个numpy数组,则需要使用np.append或其他方法。

Is there a quick way to extend arrays independently of whether they are np arrays or Python arrays? 有没有一种快速的方法可以独立于np数组还是Python数组扩展数组?

Even if your function is flexible on input, your output should be of specific type. 即使您的函数在输入上具有灵活性,您的输出也应为特定类型。 So I would just convert to desired output type. 所以我只是将其转换为所需的输出类型。

For example, if my functions is working with numpy.array and returns a numpy.array , but I want to allow list s to be input as well, the first thing I would do is convert list s to numpy.array s. 例如,如果我的函数正在使用numpy.array并返回numpy.array ,但我也想允许输入list ,那么我要做的第一件事就是将list转换为numpy.array

Like this: 像这样:

def my_func(a, b):
    a = np.asarray(a)
    b = np.asarray(b)
    # do my stuff here

NumPy's append() works on lists too! NumPy的append()也适用于列表!

>>> np.append([1,2,3], [1,2,3])
array([1, 2, 3, 1, 2, 3])

If you want to automatically make the result be the same type as the input, try this: 如果要自动使结果与输入类型相同,请尝试以下操作:

mytype = type(a)
arr = np.append(a, b)
result = mytype(arr)

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

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