python - 如何根据 Python 列表中每个元素的值创建多个列表?
问题描述
如何根据一个现有列表中的元素制作多个列表?这些新列表的名称和元素均由现有列表确定。
例如,现有列表是:
a = [2,5,4]
所需的输出是:
a_2= ['01','02']
a_5= ['01','02','03','04','05']
a_4= ['01','02','03','04']
我不确定如何循环创建不同的列表名称。有任何想法吗?
解决方案
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']
推荐阅读
- python - 在执行多处理期间,函数运行次数更多
- r - 如何使用 ggplot2 删除 facet_wrap 图中的额外列?
- vulkan - 顶点位置的 Vulkan 默认坐标系统
- javascript - React Navigation 参数不会因路线而改变的原因是什么?
- c - 如何在 C 中编写代码,要求用户正确创建至少 3 个字符和一个大写字母的密码?
- mongodb - 即使集合为空,也会出现重复错误
- php - 如果用户未登录且产品可变,则更改添加到购物车文本 Woocommerce
- haskell - 为什么接受递归模式同义词?
- node.js - PUT 和 DELETE 方法不适用于 express.js 中的参数
- c++ - 两个连接字符串中的变量名