n00bprogrammer22
n00bprogrammer22

Reputation: 187

Building a list of lists from a string

Given a specific string, my function needs to create a list of lists using all of the characters from that string. The function should start a new list whenever it sees \n in the string.

Example: build_lst("\n....\n.B.d\n") should return this list of lists: [['.','.','.','.'],['.','B','.','d']] because those 8 characters were present in the string. It creates the list of lists in the order that the characters appear in the string and as I mentioned \n divides the multiple individual lists within the main list.

My code so far is short but I think this could be accomplished with just a couple lines of code. Not sure if I am on the right track or if another strategy is better

Code:

def build_lst(s):

my_lst = s.split('\n')
[map(int) for x in my_lst] 

Upvotes: 0

Views: 91

Answers (2)

jez
jez

Reputation: 15369

A list comprehension is a nice, maintainable way to go:

[ list(line) for line in s.split('\n') ]

If blank input lines should be omitted when constructing the output, add a conditional to the list comprehension:

[ list(line) for line in s.split('\n') if line ]

...and if leading and trailing whitespace should be ignored:

[ list(line.strip()) for line in s.split('\n') if line.strip() ]

Upvotes: 0

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96287

I believe all you want is:

>>> s = "\n....\n.B.d\n" 
>>> list(map(list,s.strip().split('\n')))
[['.', '.', '.', '.'], ['.', 'B', '.', 'd']]

In Python 2, you can leave out the outer call to list and leave it at the map since map is evaluated eagerly instead of lazily as in Python 3.

Upvotes: 1

Related Questions