python - 有没有办法创建与用户输入一样多的列表?
问题描述
我想知道如何创建与用户输入一样多的列表。
假设用户输入是 4。
我想创建 4 个列表名称 Batch1 Batch2 Batch3 Batch4
从具有相同 Batch1-4.csv 名称的 csv 文件中检索数据
for i in range(1,3):
list("Batch{0}".format(i))
print(Batch1)
我已经尝试过了,但导致错误 Batch1 is not defined 因为我没有直接声明 Batch1。
你有什么解决方法吗?
解决方案
您可以像这样使用列表理解:
>>> main_list = ["batch{0}".format(i) for i in range(4)]
>>> main_list
['batch0', 'batch1', 'batch2', 'batch3']
如果您想要列表列表,请执行以下操作:
>>> main_list = [["batch{0}".format(i)] for i in range(4)]
>>> main_list
[['batch0'], ['batch1'], ['batch2'], ['batch3']]
通过用户输入,您的脚本可能如下所示:
n = int(input('Enter a number:'))
main_list = [["batch{0}".format(i)] for i in range(1,n+1)]
推荐阅读
- anylogic - 通过方法参数化模拟实验的开始/停止日期
- android - 如何在 Retrofit 中使用 GET 方法发送 json 数据?
- go - 如何比较嵌套结构,子切片字段中的字段相同但顺序不同
- sql - 为表中的每个组选择第二个最晚日期
- swift - 为什么 SecPKCS12Import 总是返回错误代码 -26275?
- c# - 如何在 EF 迁移期间根据其他列的数据填充新列?
- javascript - 如何在不使用 Bootstrap 的情况下在客户端对 JSON 数据进行分页?
- docker - Docker 桌面在 Windows 10 中启动时崩溃
- spring-boot - Spring Retry maxAttempts 不起作用
- java - Kafka Producer 发送一定数量的消息后停止发送消息