【问题标题】:Python Dictionary - using input to add up all of the values in a dictionaryPython 字典 - 使用输入将字典中的所有值相加
【发布时间】:2022-11-14 05:01:59
【问题描述】:

我已经完成了 Python 课程介绍的一半。我最近开始研究列表/字典。我试图创建自己的 python 代码来尝试学习如何更好地使用字典。基本上,我想做的是让用户输入他们在视频系列的哪个部分,然后输出系列中剩余的总时间。到目前为止,代码看起来像这样:

video_dict = {
    1 : 9,   # Section 1 is 9 minutes
    2 : 75,
    3 : 174,
    4 : 100
}

current_section = input('What section are you currently on?')

total_time = 0
for key, value in video_dict.items():
    if current_section >= key:
    total_time += value

print(total_time)
     

到目前为止,我遇到的问题是它似乎正在获取用户输入的数字并逆向输入字典。因此,如果您输入“2”作为当前部分,它会将条目 1 和 2 相加,并为您提供 84 分钟的总时间;而不是将 2,3 和 4 相加,总时间为 349 分钟。我需要更正什么才能让它在列表中而不是在列表中?

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    您的代码看起来非常接近正确。我做了一点修改,否则就是你的所有代码:

    video_dict = {
        1 : 9,   # Section 1 is 9 minutes
        2 : 75,
        3 : 174,
        4 : 100
    }
    
    
    
    current_section = input('What section are you currently on?')
    
    total_time = 0
    for key, value in video_dict.items():
        if current_section <= key:
        total_time += value
    
    print(total_time)
    

    我将current_section &gt;= key修改为current_section &lt;= key

    【讨论】:

      【解决方案2】:
      video_dict = {
          1 : 9,   # Section 1 is 9 minutes
          2 : 75,
          3 : 174,
          4 : 100
      }
      
      inp = int(input('What section are you currently on?'))
      res = 0
      for key in range(inp,0,-1):
          res+=video_dict[key]
      
      
       print(res)
      

      【讨论】:

        猜你喜欢
        • 2021-10-13
        • 1970-01-01
        • 1970-01-01
        • 2015-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-10
        相关资源
        最近更新 更多