将列表转换为列表列表
问题描述:
我想将列表转换为列表列表.示例:
I want to convert list into list of list. Example:
my_list = ['banana', 'mango', 'apple']
我想要:
my_list = [['banana'], ['mango'], ['apple']]
我尝试过:
list(list(my_list))
答
使用列表理解
[[i] for i in lst]
迭代列表中的每个项目,然后将该项目放入新列表中.
It iterates over each item in the list and put that item into a new list.
示例:
>>> lst = ['banana', 'mango', 'apple']
>>> [[i] for i in lst]
[['banana'], ['mango'], ['apple']]
如果对每个项目应用list
func,它将把字符串格式的每个项目转换为字符串列表.
If you apply list
func on each item, it would turn each item which is in string format to a list of strings.
>>> [list(i) for i in lst]
[['b', 'a', 'n', 'a', 'n', 'a'], ['m', 'a', 'n', 'g', 'o'], ['a', 'p', 'p', 'l', 'e']]
>>>