首页 > 解决方案 > 如何根据 Python 列表中每个元素的值创建多个列表?

问题描述

如何根据一个现有列表中的元素制作多个列表?这些新列表的名称和元素均由现有列表确定。

例如,现有列表是:

a = [2,5,4]

所需的输出是:

a_2= ['01','02']
a_5= ['01','02','03','04','05']
a_4= ['01','02','03','04']

我不确定如何循环创建不同的列表名称。有任何想法吗?

标签: pythonpython-3.xlist

解决方案


You can populate a dictionary with keys based on your desired variables:

a = [2, 5, 4]
output = {f"a_{i}": ["{:02d}".format(x) for x in range(1, i + 1)] for i in a}

And then you can access them easily:

print(output["a_4"]) # ['01', '02', '03', '04']

推荐阅读