首页 > 解决方案 > 如何使用循环当前引用的位置更新变量?

问题描述

我有一个输入列表,我正在使用 for 循环搜索每个值以查找最高温度以及列表中的哪个位置。

我已经完整地编写了代码,除了我不知道我会用我的循环正在查看的当前位置更新 best_position 。

    # set best_position to position
    best_position =

这就是我挣扎的地方。

# initialise the input with a non-empty list - Do NOT change the next line
temperatures = [4.7, 3, 4.8]
# set best_position to 0
best_position = 0
maxtemp = temperatures[0]
# for each position from 1 to length of list – 1:
for i in temperatures:
    # if the item at position is better than the item at best_position: 
    if maxtemp<i:
        maxtemp = i
        # set best_position to position
        best_position =
# print best_position
print(best_position, ": 00")

标签: python

解决方案


使用enumerate功能:

https://docs.python.org/3/library/functions.html#enumerate

# initialise the input with a non-empty list - Do NOT change the next line
temperatures = [4.7, 3, 4.8]
# set best_position to 0
best_position = 0
maxtemp = temperatures[0]
# for each position from 1 to length of list – 1:
for pos, t in enumerate(temperatures):
    # if the item at position is better than the item at best_position: 
    if maxtemp<t:
        maxtemp = t
        # set best_position to position
        best_position = pos
# print best_position
print(best_position, ": 00")

或者,您可以这样做:

max_temp = max(temperatures)
best_pos = temperatures.index(max_temp)
print(best_pos, ": 00")

推荐阅读