将 NumPy 数组转换为元组
Muhammad Maisam Abbas
2023年1月30日
NumPy

本教程将介绍如何在 Python 中将 NumPy 数组转换为元组。
使用 Python 中的 tuple()
函数将 NumPy 数组转换为元组
如果我们需要将 numpy 数组转换为元组,我们可以使用 Python 中的 tuple()
函数。tuple()
函数 将一个可迭代对象作为参数,并返回一个由可迭代对象的元素组成的元组。
import numpy as np
array = np.array(((0, 1), (2, 3)))
print(array)
result = tuple([tuple(e) for e in array])
print(result)
输出:
[[0 1]
[2 3]]
((0, 1), (2, 3))
我们首先使用 np.array()
函数创建了一个包含元组作为其元素的数组,并打印了 array
元素。然后,我们使用 tuple()
函数将 array
的所有元素转换为 result
元组,并打印 result
元组的元素。
使用 Python 中的 map()
函数将 NumPy 数组转换为元组
map()
函数 将特定函数应用于 Python 中的所有可迭代元素。它将要应用的函数和可迭代对象作为参数,并返回一个迭代器,其中该函数应用于可迭代对象的每个元素。我们可以使用 map()
函数将 tuple()
函数应用于 NumPy 数组的每个元素,然后将 tuple()
函数应用于结果以将它们转换为单个元组。
import numpy as np
array = np.array(((0, 1), (2, 3)))
print(array)
result = tuple(map(tuple, array))
print(result)
输出:
[[0 1]
[2 3]]
((0, 1), (2, 3))
在上面的代码中,我们使用 map(tuple, array)
函数将 array
的所有元素转换为元组,然后使用另一个 tuple()
函数将所有元组存储在一个单个元组 result
中。最后,我们打印了 result
元组的元素。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn