多维数组到多维元组

时间:2015-12-07 21:12:19

标签: python arrays multidimensional-array tuples

如果我有一个数组:

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

如何将其转换为多维元组,如

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

我试过了:

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

但最后一级未转换。

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:3)

如果您拥有大量数据,使用map会更具可读性并且实际上更有效:

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