首页 > 解决方案 > 有没有办法创建与用户输入一样多的列表?

问题描述

我想知道如何创建与用户输入一样多的列表。

假设用户输入是 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。

你有什么解决方法吗?

标签: pythonlistvariables

解决方案


您可以像这样使用列表理解:

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

推荐阅读