在列表中找到子列表项最大值的最佳方法 [英] Optimal method to find the max of sublist items within list

查看:71
本文介绍了在列表中找到子列表项最大值的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维列表,格式为:

I have a multidimensional list in the format:

list = [[1, 2, 3], [2, 4, 2], [0, 1, 1]]

如何获取所有子列表的第三个值的最大值.用伪代码:

How do I obtain the maximum value of the third value of all the sublists. In pseudo code:

max(list[0][2], list[1][2], list[2][2])

我知道这可以通过遍历列表并将第三个值提取到新列表中,然后简单地执行max(list)来完成,但是我想知道是否可以使用lambda或列表理解来完成?

I know this can be done via iterating over the list and extracting the third value into a new list, then simply performing max(list), but I'm wondering if this can be done using a lambda or list comprehension?

推荐答案

只需将max与生成器表达式一起使用:

Just use max with a generator expression:

>>> lst = [[1, 2, 3], [2, 4, 2], [0, 1, 1]]
>>> max(l[2] for l in lst)
3

此外,不要将变量命名为list,而是要隐藏类型.

Also, don't name your variables list, you are shadowing the type.

这篇关于在列表中找到子列表项最大值的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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