1

Can anyone help me with a list comprehension to split a string into a nested list of words and characters? i.e:

mystring = "this is a string"

Wanted ouput:

[['t','h','i','s'],['i','s'],['a'],['s','t','r','i','n','g']]

I've tried the following, but it doesnt split 'x' into nested list:

mylist = [x.split() for x in mystring.split(' ')]
print(mylist)
[['this'],['is'],['a'],['string']]
1

4 Answers 4

4
[list(x) for x in mystring.split(' ')]
2

You can use a nested list comprehension:

[[j for j in i] for i in mystring.split()]

Yields:

[['t', 'h', 'i', 's'], ['i', 's'], ['a'], ['s', 't', 'r', 'i', 'n', 'g']]
3
  • 1
    Or just list(map(list, mystring.split())).
    – ForceBru
    Oct 1, 2018 at 21:08
  • 1
    That's also a perfectly good solution. I figured this was more readable to the OP, that's all.
    – rahlf23
    Oct 1, 2018 at 21:09
  • 2
    Absolutely, your code is just as correct. My comment was meant to, you know, spark some admiration towards functional programming in people:)
    – ForceBru
    Oct 1, 2018 at 21:13
1

You need list(x) instead of x.split():

[list(x) for x in mystring.split()]
0

Slightly similar to other answers

map(list,mystring.split(" "))

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.