简体   繁体   English

在python中搜索嵌套列表的最有效方法是什么?

[英]What is the most efficient way to search nested list in python?

Let's say I've a nested loop where I've listed result of a particular subject of students with name like:假设我有一个嵌套循环,其中我列出了名称如下的特定学生主题的结果:

records = [[name, score]]

for example let's say we have list like these:例如,假设我们有这样的列表:

records = [['a', 67], ['b', 64], ['c', 63], ['d', 59]]

So here I want to print the maximum value with name?所以在这里我想用名字打印最大值? I'm still noob in python so it will be great if you explain in easy way.我仍然是 python 的菜鸟,所以如果你用简单的方式解释会很棒。 Thanks in advance <3提前致谢 <3

There are multiple ways of doing this.有多种方法可以做到这一点。 One of which is by using the inbuilt function max which finds the maximum value of its arguments.其中之一是使用内置函数max来查找其参数的最大值。 In this case an Array.在这种情况下是一个数组。 Since we want to get the maximum value for the score, we need to get the integer from the array.由于我们想要获得分数的最大值,我们需要从数组中获取整数。 We can do this by specifying a key function.我们可以通过指定一个键函数来做到这一点。

We can do this with an anonymous function lambda like this我们可以用这样的匿名函数 lambda来做到这一点

records = [['a', 67], ['b', 64], ['c', 63], ['d', 59]]

print(max(records, key=lambda x: x[1]))

Or we can use a defined function like this或者我们可以使用这样的定义函数

records = [['a', 67], ['b', 64], ['c', 63], ['d', 59]]
def getScore(x):
    return x[1]
print(max(records,key=getScore))

There is a simpler or more understandable way of doing this.有一种更简单或更容易理解的方法来做到这一点。 Using the library operator and its function item getter使用库操作符及其函数item getter

import operator

records = [['a', 67], ['b', 64], ['c', 63], ['d', 59]]
print(max(records,key=operator.itemgetter(1)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM