Py学习  »  Python

如何在python中创建新列表

Infeamous99 • 5 年前 • 1387 次点击  

我想从一个列表中创建新列表。下面是我正在处理的示例列表:

matrixlist = [['Matrix', '1'], ['1', '4', '6'], ['5', '2', '9'], ['Matrix', '2'], ['2', '6'], ['1', '3'], ['8', '6'], ['Matrix', '3'], ['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3'], ['Matrix', '4'], ['7', '8'], ['4', '6'], ['2', '3']]

我用for循环把它们分开:

matrix1 = [['1', '4', '6'], ['5', '2', '9']]
matrix2 = [['2', '6'], ['1', '3'], ['8', '6']]
matrix3 = [['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3']]
matrix4 = [['7', '8'], ['4', '6'], ['2', '3']]

但我想把长列表给program,它创建列表并在其中附加相关元素。就像matrix1列表中的matrix1元素。

编辑:我不能使用任何高级内置函数。我只能在代码中使用简单的函数(如append、pop、reverse、range)和我的函数。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54135
 
1387 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Ajax1234
Reply   •   1 楼
Ajax1234    5 年前

你可以用 itertools.groupby

from itertools import groupby
matrixlist = [['Matrix', '1'], ['1', '4', '6'], ['5', '2', '9'], ['Matrix', '2'], ['2', '6'], ['1', '3'], ['8', '6'], ['Matrix', '3'], ['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3'], ['Matrix', '4'], ['7', '8'], ['4', '6'], ['2', '3']]
result = [list(b) for a, b in groupby(matrixlist, key=lambda x:x[0] == 'Matrix') if not a]

输出:

[[['1', '4', '6'], ['5', '2', '9']], 
 [['2', '6'], ['1', '3'], ['8', '6']], 
 [['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3']], 
 [['7', '8'], ['4', '6'], ['2', '3']]]
Dev Khadka
Reply   •   2 楼
Dev Khadka    5 年前

你可以使用下面的列表理解

indx = [i  for i, mat in enumerate(matrixlist )if mat[0]=='Matrix']

matrixes = {matrixlist[i][1]: matrixlist[i+1: j] for i, j in zip(indx, indx[1:])}

# access matrix with its id
matrixes["1"]