python中numpy数组与list相互转换实例方法

  • Post category:Python

Python中numpy数组与list相互转换实例方法

在Python中,列表(List)和numpy数组(Array)都是常用的数据类型,它们都可以用于存储多个元素。本文将详细讲解Python中numpy数组与list相转换的实现方法,包括使用tolist()array()函数两种方法。

将numpy数组转换为list

将numpy数组转换为list需要使用tolist()函数。例如:

import numpy as np

my_array = np.array([1, 2, 3, 4, 5])

# 将numpy数组转换为list
my_list = my_array.tolist()

# 输出结果
print(my_list)  # 输出: [1, 2, 3, 4, 5]

上述代码将numpy数组my_array转换为了列表my_list

将转换为numpy数组

将list转换为numpy数组需要使用array()函数。例如:

import numpy as np

my_list = [1, 2, 3, 4, 5]

# 将list转换为numpy数组
my_array = np.array(my_list)

# 输出结果
print(my_array)  # 输出: [1 2 3 4 5]

上述代码将列表my_list转换为了numpy数组my_array

示例一:将图片转换为numpy数组并转换回list

import numpy as np
from PIL import Image

# 读取图片并转换为numpy数组
img = Image.open('test.jpg')
img_array = np.array(img)

# 将numpy数组转换为list
img_list = img_array.tolist()

# 将list转换为numpy数组
new_img_array = np.array(img_list)

# 输出结果
print(new_img_array.shape)  # 输出: (height, width, channels)

上述代码将图片test.jpg读取并转换为numpy数组img_array,然后将其转换为列表img_list,最后再将列表img_list转换为numpy数组new_img_array

示例二:将二维列表转换为numpy数组并转换回list

import numpy as np

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# 将二维列表转换为numpy数组
my_array = np.array(my_list)

# 将numpy数组转换为list
new_list = my_array.tolist()

# 输出结果
print(new_list)  # 输出: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

上述代码将二维列表my_list转换为numpy数组my_array,然后将其转换为列表new_list

以上就是Python中numpy数组与list相互转换的实现方法的详细讲解和示例说明。希望对您有所帮助。