繁体   English   中英

Python 字典 - 使用输入将字典中的所有值相加

[英]Python Dictionary - using input to add up all of the values in a dictionary

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

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 分钟的 total_time; 而不是将 2,3 和 4 加起来得到 349 分钟的总时间。 我需要更正什么才能将它放到列表下方而不是上方的 go?

您的代码看起来非常接近正确。 我做了一点修改,除此之外都是你的代码:

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



current_section = int(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 >= key to current_section <= key

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)

基本上,我想做的是让用户输入他们正在播放的视频系列的哪一部分,然后是该系列剩余的总时间 output

使用列表怎么样?

sections = [9, 75, 174, 100]

current_section = int(input('What section are you currently on?')) - 1
time_left = sum(sections[current_section:])
print(f'{time_left} minutes left')

暂无
暂无

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

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