Python:获取 IndexError:列表索引超出范围,但无法弄清楚原因

发布于 2025-01-13 14:23:53 字数 663 浏览 8 评论 0原文

我正在尝试创建一个函数,在其中查找列表输入的最高 y 值,格式为: list([x , y], [x, y]...

第 2 行,我在某处找到并复制了,我认为我有点理解它,因为它找到具有最高 y 值的嵌套列表,并将该 y 值分配给 max_value 变量,当我尝试找出嵌套列表放置在列表中的索引时,问题就出现了。发现通过使用 for循环,但我得到这个错误,并且无法理解为什么:(

第4行,在find_highest中,如果坐标([i] [1])== max_value:IndexError:列表索引超出范围)

。在这种情况下,应该有一个 0-4 之间的值,并且该值在我放入的列表的索引内。这是到目前为止我的代码:

def find_highest(coordinates):
    x_value, max_value = max(coordinates, key=lambda item: item[1])
    for i in range(len(coordinates) - 1):
        if coordinates([i] [1]) == max_value:
            index = i
    return index


print(find_highest([[96, 33], [200, 96], [30, 690], [59, 9], [220, 93]]))

I am trying to make a function where i find the highest y value of a list input with the format: list([x , y], [x, y]...

line 2, I found somewhere and copied, and i think i kind of understand it, as it finds the nested list with the highest y value, and assigns that y value to max_value variable. The issue comes when I try to find out what index that nested list is placed in the list. I try to find that by using a for loop, but i get this error, and can't understand why:

(line 4, in find_highest if coordinates([i] [1]) == max_value: IndexError: list index out of range).

From what I understand the I should have a value from 0-4 in this case, and that is within the indexes of the list I put in. Here is my code so far:

def find_highest(coordinates):
    x_value, max_value = max(coordinates, key=lambda item: item[1])
    for i in range(len(coordinates) - 1):
        if coordinates([i] [1]) == max_value:
            index = i
    return index


print(find_highest([[96, 33], [200, 96], [30, 690], [59, 9], [220, 93]]))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼泪淡了忧伤 2025-01-20 14:23:53

不知道为什么要加括号。只需将行从 更改为

    if coordinates([i] [1]) == max_value:

    if coordinates[i][1] == max_value:

就可以了。

Don't know why you have added the parentheses. Just change the line from

    if coordinates([i] [1]) == max_value:

to:

    if coordinates[i][1] == max_value:

and it should work.

何处潇湘 2025-01-20 14:23:53

您需要删除大括号:

if coordinates[i][1] == max_value:

否则,解释器将认为“坐标”是一个函数。

You need to remove the curly brackets:

if coordinates[i][1] == max_value:

otherwise, the interpreter will consider the 'coordinates' a function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文