将字符串列表插入到字符串的嵌套列表中
问题描述:
因此我需要将str列表转换为str列表的列表。将字符串列表插入到字符串的嵌套列表中
EX:
thing = [' a b c', 'e f g']
到:
[['a', 'b', 'c'], ['e', 'f', 'g']]
我的代码一直返回一个错误:
coolthing = []
abc = []
for line in thing:
abc = coolthing.append(line.split())
return abc
答
list.append
运行就地并始终返回None
。所以,abc
将返回时为None
。
做你想做什么,你可以使用一个list comprehension:
return [x.split() for x in thing]
演示:
>>> thing = [' a b c', 'e f g']
>>> [x.split() for x in thing]
[['a', 'b', 'c'], ['e', 'f', 'g']]
'返回地图(str.split,东西)'的功能apporach – 2015-04-03 19:41:01
@PadraicCunningham - +1。我实际上想过要这样做,但如果OP使用Python 3.x,则必须执行'return list(map(str.split,thing))'。关于清单比较好的事情。它在两个版本中都是一样的。 – iCodez 2015-04-03 19:43:13
你的方式可能更好的OP,只是想我会把它扔在那里。 – 2015-04-03 19:48:50