Maximum value from a list of lists and its index

房东的猫 提交于 2019-12-07 03:30:48

问题


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

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.


回答1:


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.

UPDATE

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

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))



回答2:


You can do something like:

max(data, key=lambda x: x[0])

Or, a more efficient alternative:

max(data, key=operator.itemgetter(0))

Here's the time comparison:

In [11]: timeit.timeit('max(data, key=lambda x: x[0])', setup='import operator, random; data=[[random.randint(1,100) for _ in range(100)] for _ in range(100)]')
Out[11]: 8.272005081176758

In [12]: timeit.timeit('max(data, key=operator.itemgetter(0))', setup='import operator, random; data=[[random.randint(1,100) for _ in range(100)] for _ in range(100)]')
Out[12]: 5.0041139125823975


来源:https://stackoverflow.com/questions/31772131/maximum-value-from-a-list-of-lists-and-its-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!