0

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] 
3
  • Try [list(x) for x in "\n....\n.B.d\n".strip().split("\n")]. Commented Oct 31, 2016 at 20:06
  • why map(int)? how does that relate to your expected output? Commented Oct 31, 2016 at 20:09
  • @njzk2 I'm not exactly sure I was doing some research on how to do this before asking the question and that seemed to be how it was done. I realize now that I don't need to convert to Int. Juanpa.arrivillaga's solution worked perfectly going to select his answer as best answer Commented Oct 31, 2016 at 20:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you your solution worked perfectly. I set new_lst equal to your solution 'list(map(list,s.strip().split('\n')))' and then instructed python to return new_lst and it functions correctly
0

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() ]

2 Comments

how can there be \n if you are splitting on \n?
hah! Yes, that was force-of-habit from iterating over lines read from a text file. Edited.

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.