如何使变量名依赖于python中的输入?

问题描述

我需要基于 int 输入创建多个变量,以便如果输入为 5,则创建变量,例如:worker1、worker2、worker3 等

有什么方法可以生成这样的变量,然后根据用户选择的数字向它们添加点数吗? 示例:

有多少工人? 10 -选择工人 4 -为worker4增加1点

解决方法

您可以使用字典代替使用多个变量。使用多个变量不如使用字典那么 Pythonic,并且在处理大数据时可能会很麻烦。在您的示例中,您可以使用字典来存储每个工人及其点数。 可以找到字典文档here

例如:

#recieve a valid input for the number of workers
while True:
    num = input("How many workers would you like to create?\n") # accepts an int
    try:
        num = int(num)
    except ValueError:
        print("Must input an integer")
    else:
        break

#create a dictionary with the workers and their scores (0 by default)
workers = {'worker'+str(i+1) : 0 for i in range(num)}

# get the user to choose a worker,and add 1 to their score
while True:
    worker = input("Which worker would you like to add a point to?\n") #accepts worker e.g worker1 or worker5
    if worker in workers:
        workers[worker] += 1
        print(f"Added one point to {worker}")
        break
    else:
        print("That is not a worker")

print(workers)

此代码获取用户输入以创建一定数量的工作人员。然后它获取用户输入以向其中一个工作人员添加一个点。您可以更改此设置以向不同的工作人员添加多个点,但这只是一个基本示例,这取决于您想用它做什么。