简体   繁体   English

有效地将平面列表切成多层嵌套列表

[英]Slicing flat list into multi-level nested list efficiently

For example, I have a flat list 例如,我有一个简单的清单

 [1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G']

I want to transform it into 4-deep list 我想将其转换为4深列表

[[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[9, 'A'], ['B', 'C']], [['D', 'E'] ['F', 'G']]]]

Is there a way to do it without creating a separate variable for every level? 有没有一种方法可以为每个级别创建一个单独的变量? What is the most memory- and performance-efficient way? 什么是最节省内存和性能的方法?

UPDATE: Also, is there a way to do it in a non-symmetrical fashion? 更新:另外,有没有办法以非对称的方式做到这一点?

[[[[1, 2, 3], 4], [[5, 6, 7], 8]]], [[[9, 'A', 'B'], 'C']], [['D', 'E', 'F'], 'G']]]]

Note that your first list has 15 elements instead of 16. Also, what should A be? 请注意,您的第一个列表包含15个元素而不是16个元素。此外, A应该是什么? Is it a constant you've defined somewhere else? 您在其他地方定义的常数吗? I'll just assume it's a string : 'A' . 我只是假设它是一个字符串: 'A'

If you work with np.arrays , you could simply reshape your array: 如果你有工作np.arrays ,你可以简单地重塑你的数组:

import numpy as np
r = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G'])
r.reshape(2,2,2,2)

It outputs: 它输出:

array([[[['1', '2'],
         ['3', '4']],

        [['5', '6'],
         ['7', '8']]]


       [[['9', 'A'],
         ['B', 'C']],

        [['D', 'E'],
         ['F', 'G']]]
      dtype='<U11')

This should be really efficient because numpy doesn't change the underlying data format. 这应该非常有效,因为numpy不会更改基础数据格式。 It's still a flat array, displayed differently. 它仍然是平面阵列,显示方式不同。

Numpy doesn't support irregular shapes. Numpy不支持不规则形状。 You'll have to work with standard python lists then: 然后,您必须使用标准的python列表:

i = iter([1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G'])

l1 = []

for _ in range(2):
    l2 = []
    for _ in range(2):
        l3 = []
        l4 = []
        for _ in range(3):
            l4.append(next(i))
        l3.append(l4)
        l3.append(next(i))
        l2.append(l3)
    l1.append(l2)

print(l1)
# [[[[1, 2, 3], 4], [[5, 6, 7], 8]], [[[9, 'A', 'B'], 'C'], [['D', 'E', 'F'], 'G']]]

As you said, you'll have to define a temporary variable for each level. 如您所说,您必须为每个级别定义一个临时变量。 I guess you could use list comprehensions, but they wouldn't be pretty. 我想您可以使用列表推导,但是它们并不漂亮。

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

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