Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_Nested Lists - Fatal编程技术网

Python-将列表转换为列表列表

Python-将列表转换为列表列表,python,list,nested-lists,Python,List,Nested Lists,我正在尝试创建一个列表列表,这样每个内部列表都有8个元素,在一个python单行程序中 到目前为止,我有以下几点: locations = [[alphabet.index(j) for j in test]] 映射到列表中的一个大列表: [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]] 但我想将其拆分为多个内部列表,每个列表包含8个元素: [[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]] 知道如何实现这一点吗?使

我正在尝试创建一个列表列表,这样每个内部列表都有8个元素,在一个python单行程序中

到目前为止,我有以下几点:

locations = [[alphabet.index(j) for j in test]]
映射到列表中的一个大列表:

[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]]
但我想将其拆分为多个内部列表,每个列表包含8个元素:

[[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]]

知道如何实现这一点吗?

使用带有
range()
的列表切片来获取起始索引:

In [3]: test = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

In [4]: [test[i:i+8] for i in range(0, len(test), 8)]
Out[4]: [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]
作为一项功能:

In [7]: def slicing(list_, elem_):
   ...:     return [list_[i:i+elem_] for i in range(0, len(list_), elem_)]

In [8]: slicing(test, 8)
Out[8]: [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]

另一个解决方案是使用NumPy

import numpy as np

data = [x for x in xrange(0, 64)]
data_split = np.array_split(np.asarray(data), 8)
输出:

for a in data_split:
    print a

[0 1 2 3 4 5 6 7]
[ 8  9 10 11 12 13 14 15]
[16 17 18 19 20 21 22 23]
[24 25 26 27 28 29 30 31]
[32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47]
[48 49 50 51 52 53 54 55]
[56 57 58 59 60 61 62 63]

可能的重复工作分两步进行,但有没有一种方法可以使其全部合二为一?如果不是这样的话,这将起作用,但出于学习目的,我想找到一种方法,一步完成所有工作。@user2059300好的请求-您所参考的样式称为原始答案,上面的原始答案非常好。可能也有一种itertools方法可以做到这一点。。。