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

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

问题描述

我有一个多维列表的格式:

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

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

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

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

解决方案

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

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

另外,不要给你的变量命名list,你在遮蔽类型.

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

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?

解决方案

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

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

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

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