关于python:将字符串列表转换为列表列表,列表列表中的每个元素都作为字符串中的每个可迭代字母。

Convert list of strings into list of lists with each element in list of lists as each iterable letter in string. All in one line

与list of strings X:P></

1
x = ['foo', 'bar']

我怎么能在我下面一行?P></

1
2
3
4
y = []
for word in x:
    y.append([n for n in word])
print y

导致:P></

1
[['f', 'o', 'o'], ['b', 'a', 'r']]

使用list和简单的列表理解:

1
2
3
4
>>> x = ['foo', 'bar']
>>> y = [list(word) for word in x]
>>> y
[['f', 'o', 'o'], ['b', 'a', 'r']]

或将maplist一起使用:

1
2
3
>>> y = map(list, x)
>>> y
[['f', 'o', 'o'], ['b', 'a', 'r']]

1
2
>>> map(list, ['foo', 'bar'])
[['f', 'o', 'o'], ['b', 'a', 'r']]


您可以从列表理解中的每个字符串创建一个list

1
2
3
>>> x = ['foo', 'bar']
>>> [list(i) for i in x]
[['f', 'o', 'o'], ['b', 'a', 'r']]