n00bprogrammer22 n00bprogrammer22 - 1 month ago 10
Python Question

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]

Answer

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.