2

有没有办法根据用户输入生成许多 raw_inputs(带有唯一变量)?所以,假设我有这个:

if choice == 1:
    noelemen = int(raw_input("Enter total amount of elements: "))

是否有任何方法可以使放入该 raw_input 字段中的整数然后“生成”所需数量的 raw_inputs?我想,如果可能的话,它会使用函数或类似的东西,但我对如何完成它才能做到这一点有点困惑。

我目前拥有的是这样的:

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 吗?

4

2 回答 2

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,你需要调整一些东西。

于 2012-08-15T12:11:06.290 回答
1

我会为此使用字典:

noelemen = int(raw_input("Enter total amount of elements: "))
elem={}
for x in xrange(1,noelemen+1):
    elem[x]=raw_input("Enter element: ")
于 2012-08-15T12:09:51.453 回答