查找列表的“最佳”项并在python中打印第一个实例的索引位置[重复]

Posted

技术标签:

【中文标题】查找列表的“最佳”项并在python中打印第一个实例的索引位置[重复]【英文标题】:Find the "best" item of a list and print the index position of the first instance in python [duplicate] 【发布时间】:2019-05-31 22:50:16 【问题描述】:

我需要在第一个实例上打印出列表最大值的索引位置。

我现在拥有的:

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

但是,使用上面的代码我没有得到我想要的东西,就像那个示例列表一样,我会得到 4 而不是 2 的结果。

我做错了什么?

【问题讨论】:

你不是在测试温度,只是一个任意递增的整数。 position 就是012 等等。再想一想;您如何比较实际温度?您只需在此处替换if position > best_index: 测试即可。 docs.python.org/3/library/functions.html#enumerate 可以帮到你很多。结合 max 你可以在一行中完成。 @CristiFati:看副本,有更快更好的方法。不过,我认为 OP 还没有为enumerate() 做好准备。副本在那里,因为这是潜在问题的规范答案。 最短:temperatures.index(max(temperatures)). 谢谢大家的帮助,真的很有用。抱歉打开副本! 【参考方案1】:

你做错了一些事情。首先,您正在检查新的 index 是否大于之前的 index,而不是检查实际值。其次,您打印的是索引处的实际值,而不是索引本身。

【讨论】:

这是一条评论。

以上是关于查找列表的“最佳”项并在python中打印第一个实例的索引位置[重复]的主要内容,如果未能解决你的问题,请参考以下文章