0

I want to create new lists from one list. This the example list I am working on:

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']]

I split them like this with for loop:

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']]

But I want to give the long list to program and it create lists and append the relevant elements in it. Like matrix 1 elements in matrix1 list.

Edit: I can't use any advanced built-in function. I can only use simple ones (like append, pop, reverse, range) and my functions in code.

3
  • 1
    What is wrong with the for loop approach? Are you going to have multiple matrices or there are always 4? Commented Oct 20, 2019 at 14:29
  • 1
    There is maybe more than 4. I edited the question maybe it is now clear. Commented Oct 20, 2019 at 14:35
  • If you can change the structure of the input list, I would highly recommend using a 2D array of matrices instead of the current structure. With a 2d array, your first matrix will simply be matrixList[0], the second matrixList[1], and so on. Commented Oct 20, 2019 at 14:36

2 Answers 2

1

You can use 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]

Output:

[[['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']]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks but I can't use it. I want them in different lists to use them.
0

you can do it using list comprehension like below

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"]

1 Comment

Thanks, it is useful for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.