注册 登录
编程论坛 Python论坛

请问如何把简单列表变成一个嵌套列表呢?

LanXX 发布于 2020-02-28 16:34, 1404 次点击
比如列表为[3,2,12,4,5,6,7,8,9] 变成 这种嵌套列表[[3,2,12],[4,5,6],[7,8,9]]呢?麻烦大神指导一下,谢谢,十分感谢!
2 回复
#2
benzhj2020-03-05 16:00
temp=0
list_end=[]
list_start=[3,2,12,4,5,6,7,8,9]

for i in range(3):
      list_temp=[]
      for x in range(3):
            list_temp.append(list_start[temp])
            temp=temp+1
            
      list_end.append(list_temp)

print(list_start)
print(list_end)



[3, 2, 12, 4, 5, 6, 7, 8, 9]
[[3, 2, 12], [4, 5, 6], [7, 8, 9]]

是这样吗?
#3
Log6662020-03-05 23:15
程序代码:
def lst_reshape(lst, amount=1):
    i = 0
    l = len(lst)
    newlst = []
    while l > amount:
        newlst.append(lst[i:i+amount])
        i = i+amount
        l = l-amount
    else:
        newlst.append(lst[i:])
        return newlst  

#直接输入list和step就好了
lst_test = [3,2,12,4,5,6,7,8,9]
lst_reshape(lst_test,3)
1