将字符串列表转换为列表列表,列表列表中的每个元素都作为字符串中的每个可迭代字母.一站式 [英] 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
本文介绍了将字符串列表转换为列表列表,列表列表中的每个元素都作为字符串中的每个可迭代字母.一站式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
带有字符串列表x:
x = ['foo', 'bar']
如何一行执行以下操作?
How can I do the following in one line?
y = []
for word in x:
y.append([n for n in word])
print y
结果:
[['f', 'o', 'o'], ['b', 'a', 'r']]
推荐答案
具有list
和简单的列表理解功能:
With list
and simple list comprehension:
>>> x = ['foo', 'bar']
>>> y = [list(word) for word in x]
>>> y
[['f', 'o', 'o'], ['b', 'a', 'r']]
或将map
与list
结合使用:
>>> y = map(list, x)
>>> y
[['f', 'o', 'o'], ['b', 'a', 'r']]
这篇关于将字符串列表转换为列表列表,列表列表中的每个元素都作为字符串中的每个可迭代字母.一站式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文