使用python,我想转换以下列表:
list_3_5 = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
到另一个形状--一个由6个列表组成的列表,其中前3个新列表具有来自列表_3_5中3个主列表的前3个值,然后最后3个新列表具有来自列表_3_5的剩余值:
[[1,2,3],[6,7,8],[11,12,13],[4,5],[9,10],[14,15]]
谢谢你的帮助
更新:
对于较长的列表,请执行以下操作:
list2 = [list(range(1, 34)), list(range(34, 67)), list(range(67, 100))]
list2b = [list2[i][:5] for i in range(0, len(list2))] + [
list2[i][5:] for i in range(0, len(list2))
]
还是这个
list2 = [list(range(1, 34)), list(range(34, 67)), list(range(67, 100))]
list2b = list(range(2 * len(list2)))
for key, element in enumerate(list2):
list2b[key] = element[:5]
list2b[key + len(list2)] = element[5:]
给出以下内容(将我原来的3个列表(每个列表包含33个元素)修改为6个列表,前三个列表各包含5个元素,后三个列表各包含28个元素):
[[1, 2, 3, 4, 5],
[34, 35, 36, 37, 38],
[67, 68, 69, 70, 71],
[6, 7, 8, ..., 33],
[39, 40, 41, ..., 66],
[72, 73, 74, ... 99]]
但是我想要的是这样的(在这个例子中,一个19个列表的列表,每个列表有5个元素,最后一个列表有剩余的4个元素):
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
....
....
[91, 92, 93, 94, 95],
[96, 97, 98, 99]]
看起来像这样,但我不太明白如何修改我的案例:reshape an irregular list in python
如果要使用常规代码来分隔前三个元素,请尝试以下操作:
试试这个:
输出:
下面是一个具有双for循环的解决方案,可用于任意长度的列表:
但是等等!还有更多:
以下部分回答了问题的更新部分:
输出为:
相关问题 更多 >
编程相关推荐