【问题标题】:Python - Dictionnary and tuples, retrieving key after sorted()Python - 字典和元组,在 sorted() 后检索键
【发布时间】:2014-01-30 18:48:34
【问题描述】:

例如,我有一本字典:

points_tuples = [(team1_id,team1_points),(team2_id,team2_points),(team3_id,team3_points)]

然后我使用 sorted() 方法,按点排序:

sorted_tuple = sorted(periods_tuples,key=lambda team: team[1],reverse=True) 

例如,我想获取第一名团队的团队ID...

我该怎么做?

谢谢, 阿拉

【问题讨论】:

  • 那不是字典。这是你在那里的元组列表。
  • 如果有两支球队的最大积分相同,你想发生什么?
  • @DSM,联赛平局的运作方式有点复杂,所以我将实现另一个函数来解决这个问题!

标签: python dictionary tuples sorted


【解决方案1】:

这不是字典,而是元组列表!但是您可以使用

访问第一个ID
top_score_id = sorted_tuple[0][0]

第一个零表示列表中的第一个元组,第二个表示该元组中的第一个值。

【讨论】:

    【解决方案2】:

    如果只检索第一名,则不需要排序。使用max:

    >>> points_tuples = [
    ...     ('team1', 10),
    ...     ('team2', 30),
    ...     ('team3', 20),
    ... ]
    >>> max(points_tuples, key=lambda team: team[1])
    ('team2', 30)
    >>> max(points_tuples, key=lambda team: team[1])[0]
    'team2'
    

    【讨论】:

    • 我还需要知道谁获得第二名。
    • @AraSivaneswaran,然后使用sorted_tuple[0][0],sorted_tuple[1][0] 作为其他人的回答。
    【解决方案3】:

    由于 sorted_tuple 将返回按点排序的列表,因此您可以通过 sorted_tuple[0] 获取第一个元组。根据您的元组结构,团队 ID 将是该元组的第 0 个元素。

    team_id = sorted_tuple[0][0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-05
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      相关资源
      最近更新 更多