简体   繁体   中英

How to convert nested lists into nested tuples in Python

How can I tranform this 3D list to tuple?

[[[0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0]],
 [[0, 0], [0, 0]],
 [100]]

I use this code:

tuple(tuple(tuple(j for j in i) for i in x))

but I still have [] in the result

(([0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0]),
 ([0, 0], [0, 0]),
 (100,))

My understanding is that you just want to convert nested lists into nested tuples. If this is what you need, then you'll probably need to come up with a recursive approach to deal with cases where you have an arbitrary number of nested lists.


For example,

def nested_list_to_tuple_recur(nested_list):
    return tuple(
      nested_list_to_tuple_recur(l) if isinstance(l, list) 
      else l for l in nested_list
    )

And finally call the function:

nested_list_to_tuple_recur(x)

And the output will be

(((0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0)),
 ((0, 0), (0, 0)),
 (100,))

You need to wrap 100 into another list, otherwise there are on different levels, some are packed in 2 list some only in one. If you fix that you can try this:

l = [[[0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0]],
 [[0, 0], [0, 0]],
 [[100]]]


tuple(tuple(x) for y in l for x in y)

# ((0, 0, 0, 0, 0, 0, 0, 0),
#  (0, 0, 0, 0, 0, 0, 0, 0),
#  (0, 0, 0, 0, 0, 0, 0, 0),
#  (0, 0, 0, 0, 0, 0, 0, 0),
#  (0, 0, 0, 0, 0, 0, 0, 0),
#  (0, 0, 0, 0, 0, 0, 0, 0),
#  (0, 0, 0, 0, 0, 0, 0, 0),
#  (0, 0, 0, 0, 0, 0, 0, 0),
#  (0, 0),
#  (0, 0),
#  (100,))

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