简体   繁体   English

如何将嵌套列表转换为 Python 中的嵌套元组

[英]How to convert nested lists into nested tuples in Python

How can I tranform this 3D list to tuple?如何将此 3D 列表转换为元组?

[[[0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 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:最后调用 function:

nested_list_to_tuple_recur(x)

And the output will be output 将是

(((0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 0, 0, 0, 0),
  (0, 0, 0, 0, 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.您需要将 100 包装到另一个列表中,否则有不同的级别,有些包装在 2 个列表中,有些只包装在一个列表中。 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,))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM