如何将列表和元组转换为 NumPy 数组?
在本文中,让我们讨论如何使用 NumPy 将列表和元组转换为数组。 NumPy 提供了多种方法来做同样的事情。让我们讨论一下
方法一:使用 numpy.asarray()
它将输入转换为数组。输入可以是元组列表、元组列表、元组元组、列表元组和 ndarray。
句法:
numpy.asarray( a, type = None, order = None )
例子:
Python3
import numpy as np
# list
list1 = [3, 4, 5, 6]
print(type(list1))
print(list1)
print()
# conversion
array1 = np.asarray(list1)
print(type(array1))
print(array1)
print()
# tuple
tuple1 = ([8, 4, 6], [1, 2, 3])
print(type(tuple1))
print(tuple1)
print()
# conversion
array2 = np.asarray(tuple1)
print(type(array2))
print(array2)
Python3
import numpy as np
# list
list1 = [1, 2, 3]
print(type(list1))
print(list1)
print()
# conversion
array1 = np.array(list1)
print(type(array1))
print(array1)
print()
# tuple
tuple1 = ((1, 2, 3))
print(type(tuple1))
print(tuple1)
print()
# conversion
array2 = np.array(tuple1)
print(type(array2))
print(array2)
print()
# list, array and tuple
array3 = np.array([tuple1, list1, array2])
print(type(array3))
print(array3)
输出:
[3, 4, 5, 6]
[3 4 5 6]
([8, 4, 6], [1, 2, 3])
[[8 4 6]
[1 2 3]]
方法 2:使用 numpy.array()
它创建一个数组。
Syntax: numpy.array( object, dtype = None, *, copy = True, order = ‘K’, subok = False, ndmin = 0 )
Parameters:
- object: array-like
- dtype: data-type, optional ( The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. )
- copy: bool, optional ( If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.). )
- order: {‘K’, ‘A’, ‘C’, ‘F’}, optional ( same as above )
- subok: bool, optional ( If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). )
- ndmin: int, optional ( Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement. )
Returns: ndarray ( An array object satisfying the specified requirements. )
例子:
Python3
import numpy as np
# list
list1 = [1, 2, 3]
print(type(list1))
print(list1)
print()
# conversion
array1 = np.array(list1)
print(type(array1))
print(array1)
print()
# tuple
tuple1 = ((1, 2, 3))
print(type(tuple1))
print(tuple1)
print()
# conversion
array2 = np.array(tuple1)
print(type(array2))
print(array2)
print()
# list, array and tuple
array3 = np.array([tuple1, list1, array2])
print(type(array3))
print(array3)
输出:
[1, 2, 3]
[1 2 3]
(1, 2, 3)
[1 2 3]
[[1 2 3]
[1 2 3]
[1 2 3]]