有没有办法根据用户输入生成大量raw_inputs(具有唯一变量)?所以,说我有这个:
if choice == 1:
noelemen = int(raw_input("Enter total amount of elements: "))
是否有任何方法可以使raw_input字段中的整数放入"生成"所需的raw_input数量?我认为,如果有可能的话,它会使用功能或类似的功能,但我对我如何完成它以便能够做到这一点感到困惑。
我现在所拥有的是:
if noelemen == 1:
first = raw_input("Enter element: ")
#Look for the weight of the entered element
weight1 = float(elemen_data.get(first.lower()))
if weight1 is not None:
total_weight = weight1
print "Total mass =", total_weight
if noelemen == 2:
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
#Look for the weight of the entered element
weight1 = float(elemen_data.get(first.lower()))
weight2 = float(elemen_data.get(second.lower()))
if weight1 is not None:
total_weight = weight1 + weight2
print "Total mass =", total_weight
这可能是一种非常混乱的方式,特别是因为我不得不接受类似10个元素,甚至可能超出的元素。
那么,重复一遍......根据用户输入生成具有唯一变量的raw_inputs的任何方法吗?
答案 0 :(得分:4)
这样的事情怎么样?
elements = []
numberOfPrompts = raw_input("Enter total amount of elements: ")
for i in range(numberOfPrompts):
# will prompt "Enter Element 1: " on the first iteration
userInput = raw_input("Enter Element %s" % (i+1, ))
elements.append(userInput)
>>> Enter total amount of elements: 2 # now hit enter
此时,变量numberOfPrompts
的值将为2
。
变量elements
的值将为[]
,即它是一个空列表
>>> Enter Element 1: 3.1415 # hit enter
numberOfPrompts
留下2
,
elements
将为['3.1415']
>>> Enter Element 2: 2.7182
elements
将为['3.1415', '2.7182']
现在完成for循环,您可以在0索引列表elements
中方便地获得用户输入,您可以像元组(数组)一样访问:
>>> elements[1]
2.7182
在阅读你的评论后,我注意到你打算做什么,就像其他答案所说的那样,最好使用字典。这应该有效:
elements = {}
numberOfPrompts = raw_input("Enter total amount of elements: ")
for i in range(numberOfPrompts):
# will prompt "Enter Element 1: " on the first iteration
userInput = raw_input("Enter Element %s" % (i+1, ))
userInput = userInput.lower()
elements[userInput] = float(elem_data.get(userInput))
现在elements
将如下所示:
{'oxygen':15.9994, 'hydrogen':1.0079}
你可以迭代这样的所有键(找出输入的元素):
for element in elements.keys():
print element
# output:
oxygen
hydrogen
要获取所有值(例如,总结它们),请执行以下操作:
weightSum = 0
for weight in elements.values():
weightSum += weight
print weightSum
# output:
17,0073
请记住,此示例适用于python 2.x.对于python 3.x,您需要调整一些事情。
答案 1 :(得分:1)
我会使用字典:
noelemen = int(raw_input("Enter total amount of elements: "))
elem={}
for x in xrange(1,noelemen+1):
elem[x]=raw_input("Enter element: ")