Python –将NumPy数组转换为列表

We can use numpy ndarray tolist() function to convert the array to a list. If the array is multi-dimensional, a nested list is returned. For one-dimensional array, a list with the array elements is returned.

我们可以使用numpy ndarray tolist()函数将数组转换为列表。 如果数组是多维的,则返回一个嵌套列表。 对于一维数组,将返回包含数组元素的列表。

要列出的NumPy数组 (NumPy Array to List)

The tolist() function doesn’t accept any argument. It’s a simple way to convert an array to a list representation.

tolist()函数不接受任何参数。 这是将数组转换为列表表示的简单方法。

1.将一维NumPy数组转换为列表 (1. Converting one-dimensional NumPy Array to List)

import numpy as np

# 1d array to list
arr = np.array([1, 2, 3])
print(f'NumPy Array:\n{arr}')

list1 = arr.tolist()
print(f'List: {list1}')

Output:

输出:

NumPy Array:
[1 2 3]
List: [1, 2, 3]

2.将多维NumPy数组转换为列表 (2. Converting multi-dimensional NumPy Array to List)

import numpy as np

# 2d array to list
arr = np.array([[1, 2, 3], [4, 5, 6]])

print(f'NumPy Array:\n{arr}')

list1 = arr.tolist()

print(f'List: {list1}')

Output:

输出:

NumPy Array:
[[1 2 3]
 [4 5 6]]
List: [[1, 2, 3], [4, 5, 6]]

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/32797/python-convert-numpy-array-to-list

你可能感兴趣的:(列表,python,numpy,java,算法)