将列表转换为列表列表 [英] Convert list into list of lists

查看:94
本文介绍了将列表转换为列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表转换为列表列表.示例:

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

这篇关于将列表转换为列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆