首页 > 解决方案 > 如何在python中制作数组数组?

问题描述

我有一个像['a','b','c','d','e','f']. 我怎样才能将它转换为数组数组,这样[['a','b'],['c','d'],['e','f']]

我已经尝试正常附加它,但它给出了一些随机结果

inputArr = input.split(',')
i=0
Yy = []
while i < len(inputArr):
    temp = [inputArr[i], inputArr[i+1]]
    Yy.append(temp)
    i += 2

输出:['a','b,c','d,e','f']

标签: pythonarrayslist

解决方案


我试过你的代码,没有错误。但是,如果你这样做了,你可以尝试这种方式:

new_list = [lst[i:i+2] for i in range(0, len(lst), 2)]

这输出:[['a', 'b'], ['c', 'd'], ['e', 'f']],使用列表理解,我想这是你想要的。

如果您想要 的输出[['a', 'b', 'c'], ['d', 'e', 'f']],则将 更改i:i+2i:i+3(0, len(lst), 2)在末尾更改为(0, len(lst), 3)


推荐阅读