NumPy数组与Python内建类型之间可以通过多种方式进行交互,例如:
numpy.array()
函数将Python内建类型(如列表、元组等)转换为NumPy数组。import numpy as np # 将Python列表转换为NumPy数组 my_list = [1, 2, 3, 4, 5] my_array = np.array(my_list) print(my_array)
tolist()
方法将NumPy数组转换为Python列表。import numpy as np # 将NumPy数组转换为Python列表 my_array = np.array([1, 2, 3, 4, 5]) my_list = my_array.tolist() print(my_list)
import numpy as np # 使用NumPy数组与Python内建类型进行计算 my_array = np.array([1, 2, 3, 4, 5]) result = my_array + 5 print(result)
通过以上方式,NumPy数组与Python内建类型可以方便地进行交互和操作。