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']] |
使用
1 2 3 4 | >>> x = ['foo', 'bar'] >>> y = [list(word) for word in x] >>> y [['f', 'o', 'o'], ['b', 'a', 'r']] |
或将
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']] |
您可以从列表理解中的每个字符串创建一个
1 2 3 | >>> x = ['foo', 'bar'] >>> [list(i) for i in x] [['f', 'o', 'o'], ['b', 'a', 'r']] |