【问题标题】:How do you use an input as a variable name? [duplicate]如何使用输入作为变量名? [复制]
【发布时间】:2019-05-19 20:26:49
【问题描述】:

我有这个字典:

exercise_name = {
            "sets": 3,
            "reps": 12,
            "weight": 100
}

我知道我可以通过以下方式获得用户输入:

exercise_name = input("Insert Exercise Name: ")

但是我怎样才能将我的字典直接分配给输入呢? 比如:

input("Insert Exercise Name: ") = {
    "sets": 3,
    "reps": 12,
    "weight": 100
}

我也想知道如何处理列表、集合等。

【问题讨论】:

  • 我不知道你在问什么
  • @BenjaminBreton 我希望用户提供输入。然后,我想创建一个字典并将其存储在一个等于输入的变量中。比如说,用户键入“squat”。我想要蹲下 = {}。如果用户输入“bench”,我想要 bench = {}。

标签: python python-3.x dictionary input


【解决方案1】:

不要

无论如何,您如何知道在您的程序中使用该词典?如果用户“自定义”变量名称?这听起来像xy-problem

您也可以将用户输入存储在字典中:

sillyDict = { input("Insert name") : { "sets": 3, "reps": 12, "weight": 100}}

但是为了什么目的——你打算如何使用它呢?如果你想对它做任何事情,你需要知道给定的名字或遍历整个字典。


看起来你真正需要的是classeslists

class Exercise: 
    """Capsules data for one exercise. sets/reps/weigh have defaults."""

    def __init__(self, name, sets = 3, reps = 12, weight = 100):
        """'name'd exercise with sets/reps/weight - using defaults:
        sets = 3, reps = 12, weight = 100"""
        self.name = name
        self.sets = sets
        self.reps = reps
        self.weight = weight

    def __str__(self):
         """Friendly representation of this exercise"""
         return f"{self.name}: {self.sets} sets of {self.reps} reps with {self.weight} kg"

    def __repr__(self):
         return str(self) 

# create a plan            
plan = [ Exercise("Squats"), Exercise("BenchPress",3,5,180), Exercise("Pullups",5,22,10)]

# add one by user input (fragile) - no int-validation
plan.append( Exercise(input("What to do? "), 
                      int(input("Sets: ")), 
                      int(input("Reps: ")), 
                      int(input("Weight: "))))

for exer in plan:
    print(exer)

print(plan)

输出:

What to do? Burpies
Sets: 5
Reps: 15
Weight: 0

Squats: 3 sets of 12 reps with 100 kg       # uses the default values
BenchPress: 3 sets of 5 reps with 180 kg
Pullups: 5 sets of 22 reps with 10 kg
Burpies: 5 sets of 15 reps with 0 kg

[Squats: 3 sets of 12 reps with 100 kg, BenchPress: 3 sets of 5 reps with 180 kg, 
 Pullups: 5 sets of 22 reps with 10 kg, Burpies: 5 sets of 15 reps with 0 kg]

【讨论】:

  • 我考虑过使用类和列表,但我是一个新手,还在研究 OOP。但是,是的,这似乎是最好的选择。我想没有比做更好的学习方法了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2020-11-27
  • 1970-01-01
相关资源
最近更新 更多