且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将列表转换为列表列表

更新时间:2023-02-23 09:38:12

使用列表理解

[[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']]
>>>