列表及其索引的最大值 [英] Maximum value from a list of lists and its index

查看:228
本文介绍了列表及其索引的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

li = [[1,2], [2,3], [7,6]]

如何有效地找到最大值及其索引?假设我要li:

How can I find the max value and its index efficiently? Suppose for li I want:

max_value = 7

max_index = (2, 0)

我可以按照以下步骤进行操作:

I can do this as below:

max_value = 0
for row_idx, row in enumerate(alignment_matrix):    
    for col_idx, col in enumerate(row):
        if col > max_value:
            max_value = col
            max_index = (row_idx, col_idx)

但是我需要一种有效的方法,而不必使用太多不必要的变量.

But I need an efficient way without using too many unnecessary variables.

推荐答案

使用> c1> 生成器表达式,您可以表达不久之后:

Using max and generator expression, you can express it more shortly:

max_value, max_index = max((x, (i, j))
                           for i, row in enumerate(li)
                           for j, x in enumerate(row))

但是,时间复杂度是相同的,因为这也使用了嵌套循环.

But, time complexity is same because this one also uses nested loop.

更新

正如@jonrsharpe指出的,如果重复max_value,上述解决方案将为您提供找到值的最大索引.

As @jonrsharpe pointed, in the case of duplicate max_values, above solution will give you the largest index at which the value found.

如果这不是您想要的,则可以将key函数参数传递给max以自定义行为:

If that's not what you want, you can pass key function argument to max to customize the behavior:

max_value, max_index = max(((x, (i, j))
                            for i, row in enumerate(li)
                            for j, x in enumerate(row)),
                           key=lambda (x, (i, j)): (x, -i, -j))

这篇关于列表及其索引的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆