Rojj
Rojj

Reputation: 1210

Multidimensional array to multidimensional tuple

If I have an array such:

inner_loop = 
[
 [
  [18, 119], [42, 119], [42, 95], [18, 95]
 ],
 [
  [80, 96], [80, 75], [59, 75], [59, 96]
 ]
]

how do I convert it to a multidimensional tuple like

(
 (
  (18, 119), (42, 119), (42, 95), (18, 95)
 ),
 (
  (80, 96), (80, 75), (59, 75), (59, 96)
 )
)

I have tried:

tuple(tuple(y) for y in (tuple(tuple (x) for x in (tuple(inner_loops)))))

but the last level is not converted.

Upvotes: 4

Views: 7398

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

Using map is a bit more readable and actually more efficient if you have large amounts of data:

inner_loop = tuple(tuple(map(tuple, sub)) for sub in inner_loop)

print(inner_loop)
(((18, 119), (42, 119), (42, 95), (18, 95)), ((80, 96), (80, 75), (59, 75), (59, 96)))

Upvotes: 4

Mohammad Al Alwa
Mohammad Al Alwa

Reputation: 702

tuple(tuple(tuple(l2) for l2 in l1) for l1 in inner_loop)

Upvotes: 6

Related Questions