简体   繁体   English

如何使用for循环获取用户在字典中输入的键值?

[英]How to get user inputted values for keys in dictionary with for loop?

I am trying to simplify this code that calculates total weight lost and average weight lost per month: 我正在尝试简化此代码,该代码计算每月的总失重和平均失重:

months = input("How many months have you been trying to lose weight?: ")

def weeks():
    week1 = input("How many lbs did you lose in your first week?: ")
    week2 = input("How many lbs did you lose in your second week?: ")
    week3 = input("How many lbs did you lose in your third week?: ")
    total_weight_lost = (week1)+(week2)+(week3)
    return total_weight_lost,

Can I do this using a dictionary or list? 我可以使用字典或列表吗? Something like this: 像这样:

def weeks():
    d = {"week1": 0, "week2": 0, "week3": 0}
    for k in d:
        total_weight_lost = input(" How much weight did you lose in", d, "?:")
    return total_weight_lost,

I know this is completely wrong but I am thinking there might be some way to do something like this. 我知道这是完全错误的,但是我认为可能会有某种方式来做这样的事情。 So that I can iterate through the Keys in the dictionary and get the user to provide the value without having to write the same line of code for 'week1' 'week2' and 'week3'. 这样我就可以遍历字典中的键并让用户提供值,而不必为“ week1”,“ week2”和“ week3”编写相同的代码行。 But not only that I want to repeat the function for every month the user says they were trying to lose weight and then calculate the totals. 但是,我不仅要每月重复一次该功能,用户还要说他们正在尝试减肥,然后计算总数。

You don't need a dictionary if you're not using the values. 如果不使用值,则不需要字典。 In this case, you could just use a tuple or list like so: 在这种情况下,您可以像这样使用元组或列表:

def weeks():
    d = ["week1", "week2", "week3"]
    total_weight_lost = 0
    for k in d:
        total_weight_lost += int(input(" How much weight did you lose in", d, "?:"))
    return total_weight_lost,

Even simpler might be something like this: 更简单的可能是这样的:

def weeks():
    total_weight_lost = 0
    for week in xrange(1, 4):
        total_weight_lost += int(input("How much weight did you lose in week {}?".format(week)))
    return total_weight_lost

Considering that you want to ask about three weeks, then you can simply create a loop that will ask the user that many times. 考虑到您要询问大约三个星期,那么您可以简单地创建一个循环,询问用户多次。 With a slight modification to your string, you can make this very simple without even needing a dictionary, by doing something like this: 只需对字符串稍加修改,就可以通过以下操作使此操作非常简单,甚至不需要字典:

def weeks():
    total_weight_lost = 0
    for i in range(1, 4):
        total_weight_lost += int(input("How many lbs did you lose in week {}?: ".format(i)))
    return total_weight_lost

So what we are doing in that method now is iterating starting from 1, and asking the user to enter a number for each week. 因此,我们现在在该方法中所做的工作是从1开始迭代,并要求用户输入每周的数字。 The string was changed slightly, so now we are going to use each number from the iterator of the loop to output which week number we need an entry for. 该字符串已稍作更改,因此现在我们将使用循环迭代器中的每个数字来输出需要输入哪个星期数。 For each entry, we just keep the running sum going. 对于每个条目,我们只需保持运行总和。 Then return the final result. 然后返回最终结果。

From the above solution, the things that were used can be read about below: 从以上解决方案中,可以从以下内容中读取所使用的内容:

  1. range 范围
  2. format 格式

After reading the comments in the question, I wanted to add a small variant of the answer to help clarify the comment made by Blckknght that takes a fixed number as a parameter to the method, and will ask the user that many times. 阅读问题中的注释后,我想添加一个答案的小变体,以帮助阐明Blckknght的注释 ,该注释使用固定数字作为方法的参数,并会询问用户多次。

So, if the user stated they wanted to enter how much weight they lost for 10 weeks, for example, then we are going to loop 10 times to get the entries, and we can do that, my changing the method around a bit to make it give it more context, and take an argument. 因此,例如,如果用户说要输入他们在10周内丢失的体重,那么我们将循环10次以获取条目,我们可以这样做,我将方法进行了一些更改以使它给了它更多的上下文,并引起了争论。 So weeks() can now be defined as: 因此, weeks()现在可以定义为:

total_weightloss(weeks):

Now, the method will take a parameter called weeks and we loop over that number: 现在,该方法将使用一个名为weeks的参数,我们遍历该数字:

def total_weightloss(weeks):
    total_weight_lost = 0
    for i in range(1, weeks + 1):
        total_weight_lost += int(input("How many lbs did you lose in week {}?: ".format(i)))
    return total_weight_lost

Demo: 演示:

How many lbs did you lose in week 1?: 1
How many lbs did you lose in week 2?: 2
How many lbs did you lose in week 3?: 2
How many lbs did you lose in week 4?: 2
How many lbs did you lose in week 5?: 1
How many lbs did you lose in week 6?: 2
How many lbs did you lose in week 7?: 1
How many lbs did you lose in week 8?: 1
How many lbs did you lose in week 9?: 2
How many lbs did you lose in week 10?: 1
15

The next modification you can make for this is error handling. 您可以为此进行的下一个修改是错误处理。 You can look to see how you can modify this method to make sure it only takes an integer, and what will happen if it takes a non integer value. 您可以查看如何修改此方法以确保仅采用整数,以及采用非整数值会发生什么。 Look at exception handling too, to understand how to handle these errors that could come up. 还要查看异常处理 ,以了解如何处理可能出现的这些错误。

def weeks():
    d = {"week1": 0, "week2": 0, "week3": 0}
    for i in sorted(d.keys()): 
        total_weight_lost = input(" How much weight did you lose in"+ i+ "?:")
        d[i] = total_weight_lost
    return d

You can use this .. 你可以用这个..

print sum(weeks.values())

If you need to use the dictionary to keep track of the weight per week (ie maybe you need the values later to perform some other calculations) you can do something like this 如果您需要使用字典来跟踪每周的重量(例如,也许以后需要这些值来执行其他一些计算),则可以执行以下操作

weeks = {"week1": 0, "week2": 0, "week3": 0}

for key in weeks:
    total_weight_lost = input(" How much weight did you lose in {}".format(key))
    weeks[key] = float(total_weight_lost)

#total weight lost over all weeks
print sum(weeks.values())

however if you just need a sum of the total weight lost then you can use one of the other answers. 但是,如果您只需要总重量的总和,则可以使用其他答案之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM