0

如何将字符串列表转换为列表列表

a=['A','B','C']

并转换为

b=[['A'],['B'],['C']]
4

2 回答 2

13

使用列表理解

In [7]: a = ['A', 'B', 'C']

In [8]: b = [[item] for item in a]

In [9]: b
Out[9]: [['A'], ['B'], ['C']]
于 2012-10-28T13:52:24.870 回答
7

使用列表理解:

>>> a=['A','B','C']
>>> [list(x) for x in a]
[['A'], ['B'], ['C']]

或 use map(),在 python 3.x 中map()返回一个地图对象,所以list(map(list,a))在那里使用:

>>> map(list,a)
[['A'], ['B'], ['C']]

或者正如@mata 指出的那样,如果你想要这样的东西:

>>> a=['foo','bar','spam']
>>> [[x] for x in a]
[['foo'], ['bar'], ['spam']]

或与map()

In [1]: a=['foo','bar','spam']

In [2]: map(lambda x:[x],a)
Out[2]: [['foo'], ['bar'], ['spam']]
于 2012-10-28T13:52:43.437 回答