簡體   English   中英

如何在python 3中將2D數組轉換為元組?

[英]How can I convert a 2D array into a tuple in python 3?

類型轉換

我有一個大小為667000 * 3的numpy數組,我想將其轉換為667000 * 3元組。

在較小的尺寸中,這就像將arr轉換為t一樣,其中:

arr= [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

t= ((1,2,3),(4,5,6),(7,8,9),(10,11,12))

我努力了 :

t = tuple((map(tuple, sub)) for sub in arr)   

但是沒有用

您能幫我在python 3中怎么做嗎?

您無需遍歷sub ,只需首先將每個子列表包裝在元組中,然后將結果包裝在元組中,例如:

tuple(map(tuple, arr))

例如:

>>> arr = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
>>> tuple(map(tuple, arr))
((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12))

因此,這里map將生成一個生成器,該生成器將為每個子列表(如[1, 2, 3] )將其轉換為元組(如(1, 2, 3) )。 然后,外部tuple(..)構造函數將此生成器的元素包裝在一個元組中。

根據實驗,轉換667000×3矩陣是可行的。 當我為np.arange(667000*3)np.random.rand(667000, 3) np.arange(667000*3)運行此np.random.rand(667000, 3)它需要0.512秒:

>>> arr = np.random.rand(667000,3)
>>> timeit.timeit(lambda: tuple(map(tuple, arr)), number=10)
5.120870679005748
>>> arr = np.arange(667000*3).reshape(-1, 3)
>>> timeit.timeit(lambda: tuple(map(tuple, arr)), number=10)
5.109966446005274

一個簡單的迭代解決方案是使用生成器表達式:

tuple(tuple(i) for i in arr)
# ((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM