For example I have the list like:

a = [143, 146, 152, 235, 246, 468, 476, 607, 615, 707, 712]

我想把它改成二维形式:
b = [
    [143, 146, 152],
    [235, 246],
    [468, 476],
    [607, 615],
    [707, 712]
]

或:
"143 146 152
235 246
468 476
607 615
707 712"

但是从形状listlist开始
如何实现这个目标?
我有这样的东西:
devu = ''
for i in b:
    for j in range(i):
        devu += str(b[j])

devu += ' '
print(devu)

但结果是:
143146152 143146 143146 143146 143146

最佳答案

。使用iter和一个简单的迭代。
演示:

a=[143, 146, 152, 235, 246, 468, 476, 607, 615, 707, 712]
a = iter(a)
shape =[3,2,2,2,2]

result = []
for s in shape:
    temp = []
    for i in range(s):
        temp.append(next(a))
    result.append(temp)
print(result)

Output:
[[143, 146, 152], [235, 246], [468, 476], [607, 615], [707, 712]]

关于python - 如何从列表中获取二维列表,但形状在另一个列表中定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56077676/

10-11 07:17