添加字典项,同时循环

时间:2018-09-22 19:59:34

标签: python

我不确定spent等于什么。我正在尝试为每个键添加[2]词典项目。

movies = {
1:('The Shawshank Redemption' , 'Bob', 25, 5),
2:('The Godfather', 'Kelly', 25, 4),
3:('The Dark Knight', 'Tyler', 25, 3),
4:('12 Angry Men', 'Bob', 25, 4),
5:('The Shawshank Redemption' , 'Bill', 35, 4),
6:('The Godfather', 'Sally', 35, 5),
7:('The Dark Knight', 'Suzy', 19, 5),
8:('12 Angry Men', 'Frank', 19, 3),
9:('The Shawshank Redemption' , 'Sally', 35, 5),
10:('The Godfather', 'Leslie', 40, 2),
11:('The Green Knight', 'Tom', 35, 2),
12:('14 Angry Men', 'Kaitlyn', 25, 4)}

spent = 
x = 1
while spent < max(movies.keys()):
   spent += movies[x][2]
    x += 1
else:
   print ('The total money spent is:', spent)

1 个答案:

答案 0 :(得分:1)

您不应该将spent与任何东西进行比较,它只包含总数。使用for循环遍历字典元素。

循环中无需增加x,这只是字典中元素的数量,您可以使用len()获得。

spent = 0
x = len(movies)
for movie in movies.values():
    spent += movie[2]
print('The total money spent is:', spent)

您还可以将内置sum()函数与列表理解结合使用。

spent = sum(movie[2] for movie in movies)

等效的while循环需要将x与字典元素的数量进行比较:

x = 1
spent = 0
while x <= len(movies):
    spent += movies[x][2]
    x += 1

这假定字典键是从1开始的序号。通常,您将使用类似这样的列表,当键的顺序较少时,将使用字典。如果是列表,则必须调整以考虑从0而不是1开始的列表索引:

x = 0
spent = 0
while x < len(movies):
    spent += movies[x][2]
    x += 1
相关问题