Reputation: 3
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,))
Upvotes: 0
Views: 416
Reputation: 9217
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,))
Upvotes: 0
Reputation: 39955
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,))
Upvotes: 2