我希望将用户输入的字符串组合为一个变量(当然是动态的)并使用它来制作另一个变量。
示例:
x = str(input("What do you want to buy? "))
(我希望新变量与x_cost
类似 - 但当然你并没有真正写出来这样做)
让我们说用户输入apple,因此新变量将是:apple_cost
。
有办法做到这一点吗?
答案 0 :(得分:2)
你应该使用dict。我知道如果你以前从未见过它,很难理解dict是什么,但是如果你想学习,那么放慢速度并理解这些东西是绝对必要的。
costs = {}
item_name = input("What do you want to buy? ")
costs[item_name] = input('Price? ')
所以你可以尝试输入一些东西
costs = {}
for i in range(4):
item_name = input("What do you want to buy? ")
costs[item_name] = input('Price? ')
如果你不知道名字,你会如何打印出所有这些新变量?用dict很容易:
for key, value in costs.items():
print(key, "costs", value)
答案 1 :(得分:1)
解决这个问题的一个好方法是使用字典。字典“条目”包含两个对象,一个键和一个项目。你可以把钥匙看作神奇的单词,将项目看作精灵 - 通过调用钥匙(即说出神奇的单词)你可以引用一个项目(即召唤精灵)。
让我们来看看水果的例子。如果您希望用户输入三种水果之一(例如apple
,pear
和cantaloupe
)并使其与价格相对应。如果我们说苹果花费1美元,梨花2和哈密瓜一百,那么这就是我们的字典看起来像:
#This is our dictionary. you can see the keyword (the fruit) goes first
#in order to summon the price, which we will store in another variable
fruit_dict = {'apple': 1.00, 'pear': 2.00, `cantaloupe`: 100.00}
现在我们有一个有效的字典,让我们编写一个程序!
#First we define the dictionary
fruit_dict = {"apple": 1.00, "pear": 2.00, "cantaloupe": 100.00}
#Now we need to ask for user input
fruit = raw_input("What fruit would ya like?\n>>> ")
#Next, we look for the fruit in our dictionary. We will use a function
#called `values()`, which returns `True` or `False`.
if fruit in fruit_dict:
fruit_cost = fruit_dict[fruit] #accessing the value with dictname[key]
这很容易!现在,您可以使用变量执行所需的操作。
祝你好运,编码愉快!
答案 2 :(得分:0)
您无法动态创建变量名称。
您需要的是dictionary。
有两种方法可以达到你想要的效果
mydict = {}
x = str(input("What do you want to buy? "))
mydict[str(x)+'_cost'] = 'some value'
从安全的角度来看,现在直接使用用户输入来填充字典可能是一项有风险的业务,因此您可能需要这样做:
import hashlib
mydict = {}
x = str(input("What do you want to buy? "))
hashkey = hashlib.md5(str(x)).hexdigest()
mydict[hashkey+'_cost'] = 'some value'
答案 3 :(得分:0)
在python中,一切都是对象。程序从主模块 main 开始。每个模块,类等都有自己的命名空间(字典),其中定义了变量。因此,如果你在该命名空间dict中放入一个键,那么它就变成了变量。您可以使用该变量指向您想要的任何其他对象。
看看这段代码......
在python交互模式下试试....
import sys
sys.modules['__main__'].__dict__ # this is your main modules namespace.
因此,只需将变量名称作为键输入到dict中,然后分配值/ object。
sys.modules['__main__'].__dict__['apple_cost']]
apple_cost = 10.5
你可以访问任何容器类/ modules / etc的命名空间......但是我不建议你做我解释的事情(这只是一种做法。有点hacky /丑陋)而是使用描述符或一个类中的简单getattr方法(有点高级,但有些东西可以学习)来实现这样的东西。