LeeXiaoLong
LeeXiaoLong

Reputation: 35

make a matrix from a list in python

I have a problem with a list in python that I need to convert to a matrix. The list is always random so I have no Idea how to make it. Here's an example :

['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '\n', '1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1', '\n', '1', ' ', ' ', '1', ' ', ' ', '1', '1', '1', '1', '\n', '1', ' ', ' ', '1', ' ', ' ', ' ', ' ', ' ', '1', '\n', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '\n', '\n']


And I want it to look like a matrix so that for each '\n' it would make a new list :

[['1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1'], ['1', ' ', ' ', '1', ' ', ' ', '1', '1', '1', '1'], ['1', ' ', ' ', '1', ' ', ' ', ' ', ' ', ' ', '1'], ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']]


I have no idea how to make this so somebody could help please?

Upvotes: 1

Views: 108

Answers (2)

user3483203
user3483203

Reputation: 51155

You can use itertools.groupby:

from itertools import groupby

def split_at_el(arr, el):
    return [list(j) for i,j in groupby(arr,lambda x: x == el) if not i]

x = ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '\n', '1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1', '\n', '1', ' ', ' ', '1', ' ', ' ', '1', '1', '1', '1', '\n', '1', ' ', ' ', '1', ' ', ' ', ' ', ' ', ' ', '1', '\n', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '\n', '\n']

print(split_at_el(x, '\n'))

Output:

[['1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1'], ['1', ' ', ' ', '1', ' ', ' ', '1', '1', '1', '1'], ['1', ' ', ' ', '1', ' ', ' ', ' ', ' ', ' ', '1'], ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']]

Also works for any longer strings:

>>> split_at_el(['hello', 'there', '\n', 'more', 'strings'], '\n')
[['hello', 'there'], ['more', 'strings']]

Upvotes: 3

rafaelc
rafaelc

Reputation: 59274

You can also use list comprehension

[list(k) for k in "".join(c).split("\n") if k]

Upvotes: 1

Related Questions