将列表转换为列表列表

时间:2012-10-28 13:51:03

标签: python python-3.x

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

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

并转换为

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

2 个答案:

答案 0 :(得分:13)

使用list comprehension

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

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

In [9]: b
Out[9]: [['A'], ['B'], ['C']]

答案 1 :(得分:7)

使用列表理解:

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

或使用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']]