Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将普通列表转换为特定嵌套列表_Python_List_Python 2.7 - Fatal编程技术网

Python 将普通列表转换为特定嵌套列表

Python 将普通列表转换为特定嵌套列表,python,list,python-2.7,Python,List,Python 2.7,我在python中有一个类似的列表:[a,b,c,d,e,f,g,h,I]。我想将此列表转换为列表列表(嵌套列表)。第二级列表应包含四个元素。因此,新列表应如下所示: [ [a,b,c,d], [e,f,g,h], [i], ] 有没有类似蟒蛇的方法?我将不得不这样做几次,所以如果有人知道一种不使用数百个索引的方法,我会很高兴 您可以使用,并且: 你需要使用切片。尝试类似于[a,b,c,d,e,f,g,h,i][4:4]的方法,看看它能做什么。 >>> lst =

我在python中有一个类似的列表:
[a,b,c,d,e,f,g,h,I]
。我想将此列表转换为列表列表(嵌套列表)。第二级列表应包含四个元素。因此,新列表应如下所示:

[
  [a,b,c,d],
  [e,f,g,h],
  [i],
]
有没有类似蟒蛇的方法?我将不得不这样做几次,所以如果有人知道一种不使用数百个索引的方法,我会很高兴

您可以使用,并且:


你需要使用切片。尝试类似于
[a,b,c,d,e,f,g,h,i][4:4]
的方法,看看它能做什么。
>>> lst = ['a', 'b', 'c', 'd', 'e',' f', 'g',' h', 'i']
>>> n = 4  # Size of sublists
>>> [lst[x:x+n] for x in xrange(0, len(lst), n)]
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i']]
>>>