【问题标题】:What is the most efficient way to search nested list in python?在python中搜索嵌套列表的最有效方法是什么?
【发布时间】:2020-10-04 01:31:14
【问题描述】:

假设我有一个嵌套循环,我在其中列出了具有姓名的学生的特定科目的结果 喜欢:

records = [[name, score]]

例如,假设我们有这样的列表:

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

所以我想在这里打印带有名称的最大值? 我仍然是python中的菜鸟,所以如果你用简单的方式解释会很棒。 提前感谢

【问题讨论】:

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

标签: python list search nested-lists


【解决方案1】:

有多种方法可以做到这一点。 其中之一是使用内置函数max,它可以找到其参数的最大值。在这种情况下是一个数组。由于我们想获得分数的最大值,我们需要从数组中获取整数。我们可以通过指定一个键函数来做到这一点。

我们可以通过anonymous function lambda 做到这一点 像这样

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

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

或者我们可以像这样使用定义的function

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

有一种更简单或更容易理解的方法。使用库operator及其函数item getter

import operator

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

【讨论】:

  • 别忘了operator.itemgetter :)
  • 呵呵,不知道。更新我的答案以包含它:D 谢谢@revliscano
  • 你是什么意思?标记?
  • 我的意思是分数,忘了我在主帖里写了分数对不起
  • print(max(records, key=lambda x: x[1])[0]) 喜欢这样吗?
猜你喜欢
  • 2012-08-11
  • 2012-01-02
  • 2017-05-26
  • 2012-03-24
  • 2015-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
相关资源
最近更新 更多