简体   繁体   中英

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

type conversion

I have a numpy array of dimensions 667000 * 3 and I want to convert it to a 667000*3 tuple.

In smaller dimensions it would be like converting arr to t, where:

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))

I have tried :

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

but didn't work.

Can you help me how can I do that in python 3?

You do not need to iterate over the sub , just first wrap every sublist in a tuple, and then wrap that result in a tuple, like:

tuple(map(tuple, arr))

For example:

>>> 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))

Here map will thus produce an generator that for each sublist (like [1, 2, 3] ) will convert it to a tuple (like (1, 2, 3) ). The outer tuple(..) constructor than wraps the elements of this generator in a tuple.

Based on an experiment, converting a 667000×3 matrix is feasible. When I run this for an np.arange(667000*3) and np.random.rand(667000, 3) it requires 0.512 seconds:

>>> 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

A simple iterative solution to your problem would be to use a generator expression:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM