简体   繁体   English

使用 python 在列表的给定部分中查找最大数字的索引

[英]Find the index of the biggest number in a given part of a list with python

I'm trying to get the index of the biggest number in a part of the list, like that:我正在尝试获取列表一部分中最大数字的索引,如下所示:

if the list is this:如果列表是这样的:

91 71 52 38 17 14 91 43 58 50 27 29 48 91 71 52 38 17 14 91 43 58 50 27 29 48

I'm doing this with i = 5. (So I would think my code snippet should have to choose between 14 and 91)我正在使用 i = 5 执行此操作。(所以我认为我的代码片段应该必须在 14 和 91 之间进行选择)

i = linelist.index(max(linelist[i:i+2]))

What I would like after my statement is i= 6 (corresponding to the second occurrence of 91) but it keep giving me 0, for the first occurence of 91. Is there anyway to have my code choosing the index in the part of the list I'm feeding to it?在我的声明之后我想要的是 i = 6(对应于 91 的第二次出现)但它一直给我 0,因为第一次出现 91。无论如何我的代码在列表的一部分中选择索引我喂它?

Thanks谢谢

You can determine the index relative to the slice that you passed to max() and then add the base index of the slice:您可以确定相对于您传递给max()的切片的索引,然后添加切片的基本索引:

slice = linelist[i:i+2]
i = i + slice.index(max(slice))

Here's the easy way to do it.这是一个简单的方法。 You are missing the addition of i您缺少i的添加

x = [91, 71,  52, 38, 17, 14, 91, 43,  58, 50, 27, 29, 48]

for i in range(0, len(x)):
    temp_list = x[i: i+2]
    max_list = max(temp_list)
    max_index = i + temp_list.index(max_list)
    print(max_index)

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

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