Python从列表创建子列表的列表 [英] Python Create a list of sublists from a list
本文介绍了Python从列表创建子列表的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下列表
colors = {a, b, c}
n = 3
颜色和n都是动态生成的.我想使用 n
和该列表的元素创建一个子列表,以获取以下信息:
Where both colors and n are built dynamically. I want to create a sublist using n
and the elements of the list to get the following:
lcolors = [[a, a, a], [b, b, b], [c, c, c]]
如果颜色
不是动态的,那很简单:
if colors
wasn't dynamic, it was easy:
lcolors = [[a]*n, [b]*n, [c]*n]
我尝试过:
lcolors = colors * n
但这给了我一个包含9个项目的列表,而不是3个每个包含3个项目的子列表:
but that gave me a single list with 9 items instead of 3 sub-lists with 3 items each:
lcolors = [a, b, c, a, b, c, a, b, c]
此处提供的解决方案都不能解决此问题:
None of the solutions offered here solve this:
推荐答案
如果我理解正确,则可以使用列表理解:
If I understood correctly, you can use list comprehension:
lcolors = [[color] * n for color in colors]
这篇关于Python从列表创建子列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文