Python 如何根据用户输入的数字创建多个变量

Python 如何根据用户输入的数字创建多个变量,python,loops,Python,Loops,我正在创建一个脚本,询问用户希望比较多少数据集 用户输入一个数字,我想知道是否有一种方法,使用循环,为用户输入的数字创建许多变量 input_SetNum = input("How many data sets are you comparing: ") print ("You entered " + input_SetNum) data_sets = {} for i in range(1, input_SetNum+1): data_sets[i] = input("Please ent

我正在创建一个脚本,询问用户希望比较多少数据集

用户输入一个数字,我想知道是否有一种方法,使用循环,为用户输入的数字创建许多变量

input_SetNum = input("How many data sets are you comparing: ")
print ("You entered " + input_SetNum) 

data_sets = {}
for i in range(1, input_SetNum+1):
data_sets[i] = input("Please enter the file path a data set: ")

只需使用一个列表,每个数字对应一个元素。

您可以使用

for i in input_SetNum:
    vars()["var%s=value" % (i)] = value
从长远来看,您可能希望将其放在类中,其中类的变量由

class SomeObj:
    def __init__(self, input_SetNum, values):
        for i in input_SetNum:
            vars(self)["var%s=value" % (i)] = values[i]

你可以用字典

data_sets = {}
for i in range(1, input_SetNum+1):
    data_sets[i] = # data set value here
编辑:

如果您使用的是Python 3,那么完整的代码应该是:

input_SetNum = input("How many data sets are you comparing: ")
print ("You entered " + input_SetNum) 

data_sets = {}
for i in range(1, int(input_SetNum)+1):
    data_sets[i] = input("Please enter the file path a data set: ")

print(data_sets)
当输入3时,打印数据集将产生此结果:

{1: '/path/file1', 2: '/path/file2', 3: '/path/file3'}
如果您使用的是Python2.7,那么应该将所有
input()
s替换为
raw\u input
s


编辑2:

要根据CSV文件的路径打开CSV文件,您可以在已经完成的操作中使用类似的代码

for key in data_sets:
    with open(data_sets[key]) as current_file:
        # do stuff here
也可以在以前用于文件路径的
input()
上使用
open()

data_sets[i] = open(input("Please enter the file path a data set: "))

我不能100%确定这是否有效,因为我对CSV文件不是很熟悉,但这不会有什么坏处,如果有效,比较数据集会更容易。

你肯定走对了路。您的代码与我为同一任务生成的代码没有多大区别。我的大多数改变都是出于偏好,主要是我会使用列表而不是字典,因为在这种情况下似乎没有任何压倒性的理由使用字典;您似乎主要是以与使用其他语言中的数组相同的方式使用它,或者作为不需要显式地
.append()
.extend()
将新项添加到的列表来使用它

# Python 3.  For Python 2, change `input` to `raw_input` and modify the
# `print` statement.
while True:  # Validate that we're getting a valid number.
    num_sets = input('How many data sets are you comparing?  ')

    try:
        num_sets = int(num_sets)

    except ValueError:
        print('Please enter a number!  ', end='')

    else:
        break

data_sets = []

# Get the correct number of sets.  These will be stored in the list,
# starting with `data_sets[0]`.
for _ in range(num_sets):
    path = input('Please enter the file path a data set:  ')
    data_sets.append(path)
如果为集合数输入
3
,则将
data\u set
设置为

['data_set_0', 'data_set_2', 'data_set_3']

获取适当的输入。

谢谢,这非常有帮助!不过我有两个问题。1.我得到一个错误,关于第5行“不能隐式地将int对象转换为str”。二,。随着for循环的进行,我是否可以要求用户输入其csv数据文件的文件位置?我更新了代码,向上显示了我的意思。再次感谢您的帮助。@user1810514您使用的是哪一版本的Python?