寻找最有价值的位置

时间:2019-01-06 01:54:57

标签: python

因此,我遇到了编写代码的问题,该代码将在列表示例中找到最佳值位置,因为最好的值是列表中的第一个数字,然后我希望它返回(或使变量成为打印)将为0。 我拥有的代码目前无法正常工作,我们将不胜感激

temperatures = [4.7, 3, 4.8]
best_position = temperatures[0]
# for each position from 1 to length of list – 1:
for temperature in temperatures[-1]:
    if temperature > best_position:
        best_position = temperature
print(best_position)

1 个答案:

答案 0 :(得分:0)

您当前正在尝试循环访问单个元素,因为temperatures[-1]表示列表的最后一个元素。如果这样做,您将获得

  

TypeError:“ float”对象不可迭代

由于需要索引,因此应首先使用0作为第一个元素的best_position。然后,您应该遍历整个列表,因为您不想与列表中的所有其余项进行比较。使用enumerate也会为您提供索引

temperatures = [4.7, 3, 4.8]
best_position = 0

for i, temperature in enumerate(temperatures):
    if temperature > temperatures[best_position]:
        best_position = i
print(best_position)
# 2
相关问题