有人可以通过列表理解帮助我将字符串拆分为单词和字符的嵌套列表吗?即:
mystring = "this is a string"
想要的输出:
[['t','h','i','s'],['i','s'],['a'],['s','t','r','i','n','g']]
我尝试了以下操作,但是它不会将'x'拆分为嵌套列表:
mylist = [x.split() for x in mystring.split(' ')]
print(mylist)
[['this'],['is'],['a'],['string']]
答案 0 :(得分:3)
[list(x) for x in mystring.split(' ')]
答案 1 :(得分:2)
您可以使用嵌套列表理解:
[[j for j in i] for i in mystring.split()]
收益:
[['t', 'h', 'i', 's'], ['i', 's'], ['a'], ['s', 't', 'r', 'i', 'n', 'g']]
答案 2 :(得分:1)
您需要list(x)
而不是x.split()
:
[list(x) for x in mystring.split()]
答案 3 :(得分:0)
与其他答案类似
center.innerHTML = width * 1 + '%';