简体   繁体   中英

Convert List of list into tuple of tuples

I have a list of 2x1 matrices like:

[[[2.3], [2.4]], [[1.7], [1.6]], [[2.02], [2.33]]]

I need to convert it into a tuple of tuples, like:

((2.3,2.4),(1.7,1.6),(2.02,2.33))

I know I can loop through the list and convert it manually, trying to check if there is a better-optimized way of doing it.

Using nested list comprehension:

orig = [[[2.3], [2.4]], [[1.7], [1.6]], [[2.02], [2.33]]]
>>> tuple(tuple(e[0] for e in l) for l in orig)
((2.3, 2.4), (1.7, 1.6), (2.02, 2.33))

You can do it this way using numpy indexing and slicing that outer dimension.

ma =  [[[2.3], [2.4]], [[1.7], [1.6]], [[2.02], [2.33]]]
ama=np.array(ma) #incase it wasn't a numpy array since you mentioned numpy in tags
tuple(map(tuple,ama[:, :, 0].tolist()))

Output:

((2.3, 2.4), (1.7, 1.6), (2.02, 2.33))
L = [[[2.3], [2.4]], [[1.7], [1.6]], [[2.02], [2.33]]]
tuple(tuple(l2[0] for l2 in l1) for l1 in L)

Output:

((2.3, 2.4), (1.7, 1.6), (2.02, 2.33))

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