欢迎访问宙启技术站
智能推送

Python中from_array()函数的源码解读与理解

发布时间:2024-01-09 04:31:19

在Python中,from_array()是一个NumPy函数,用于将一个array-like的对象(例如列表或元组)转换为一个NumPy数组。它接受两个参数:objectdtype

object参数是指要转换为NumPy数组的array-like对象。它可以是列表、元组、数组、字符串等。

dtype参数是可选的,用于指定返回的NumPy数组的数据类型。如果不指定,NumPy将尝试根据object参数的内容来推断数据类型。

下面是from_array()函数的源代码实现:

def from_array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
    if isinstance(object, ndarray):
        if dtype is not None and dtype != object.dtype.descr:
            return object.astype(dtype)
        elif subok and dtype is None:
            return object
        else:
            return object.copy(order)
    if isinstance(object, str) or not isinstance(object, collections.Iterable):
        try:
            array = numpy.array(object, dtype=dtype, copy=copy, order=order, ndmin=ndmin)
        except TypeError:
            raise TypeError("Input must be a list or a string")
    else:
        try:
            array = numpy.array(object, dtype=dtype, copy=copy, order=order, subok=subok, ndmin=ndmin)
        except TypeError:
            array = numpy.array(list(object), dtype=dtype, copy=copy, order=order, ndmin=ndmin)
    return array

上述代码首先判断object是否已经是一个NumPy数组,如果是,则根据提供的dtype参数进行相应的转换,并返回该数组。

如果object不是NumPy数组,代码会检查object是否是一个字符串或者一个不可迭代的对象(例如数字)。如果是,将object转换为NumPy数组并返回。

如果object既不是NumPy数组,也不是字符串或不可迭代对象,代码会先尝试将object转换为NumPy数组并返回。如果抛出了TypeError异常,则将object转换为列表,并再次尝试将其转换为NumPy数组。

下面是一个使用from_array()函数的示例:

import numpy as np

# 使用列表创建数组
lst = [1, 2, 3, 4, 5]
arr = np.from_array(lst)
print(arr)  # 输出: [1 2 3 4 5]

# 使用元组创建数组,并指定数据类型为浮点数
tpl = (1.1, 2.2, 3.3, 4.4, 5.5)
arr = np.from_array(tpl, dtype=np.float)
print(arr)  # 输出: [1.1 2.2 3.3 4.4 5.5]

# 使用字符串创建数组
str = "hello"
arr = np.from_array(str, dtype=np.character)
print(arr)  # 输出: [b'h' b'e' b'l' b'l' b'o']

# 使用数组创建数组,并指定数据类型为复数
arr1 = np.array([1, 2, 3])
arr2 = np.from_array(arr1, dtype=complex)
print(arr2)  # 输出: [1.+0.j 2.+0.j 3.+0.j]

以上示例演示了使用不同的array-like对象创建NumPy数组的过程。在每个示例中,from_array()函数将输入的对象转换为一个NumPy数组,并根据指定的数据类型返回相应的数组。