將 NumPy 陣列轉換為元組
Muhammad Maisam Abbas
2023年1月30日

本教程將介紹如何在 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
元組的元素。
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