【问题标题】:List of tuples that have race times. Need to list the name and time of the winner for each race具有比赛时间的元组列表。需要列出每场比赛获胜者的姓名和时间
【发布时间】:2019-04-09 00:22:31
【问题描述】:

我正在研究 Python 3。需要帮助来整理逻辑以了解谁赢得了比赛。

results_2002 = [("John Williams", "USA", 5.5),("Jim Newsom",
"Canada", 6.1), ("Paul Smith", "Netherlands", 5.3)

results_2004 = [("Simon Dent", "Canada", 6.2),("Stan Doe", "USA",
6.1), ("Paul Smith", "Netherlands", 5.4)

def find_winner(results):

    #I need help with the logic of figure out who won these two races

    return

find_winner(results_2002)
find_winner(results_2004)

我一直在尝试对元组进行反向排序并打印出它给出的第一个赛车手,但我遇到了错误,或者它只会列出第一次放入列表的时间。

【问题讨论】:

标签: python python-3.x list sorting tuples


【解决方案1】:

您可以使用built-in method : sorted根据某个键对您的列表进行排序。

unsorted_list = [("John Williams", "USA", 5.5),("Jim Newsom","Canada", 6.1), ("Paul Smith", "Netherlands", 5.3)]

# sort with regards to 3d entry of the tuple
sorted_list = sorted(unsorted_list, key=lambda x:x[2]) #
print(sorted_list)

输出:

[('保罗史密斯', '荷兰', 5.3), (“约翰·威廉姆斯”,“美国”,5.5), ('吉姆纽森','加拿大',6.1)]

获胜者是列表的第一个元素或最后一个元素。如果您的元组中的整数是时间,我想这是第一个。

def first_place(results):
  """ return the first place if any."""

  sorted_results = sorted(unsorted_list, key=lambda x:x[2])
  return next(iter(sorted_results), None)

【讨论】:

    【解决方案2】:

    您还可以使用max(或min,具体取决于您的获胜标准)和key,指定在确定最大值(或最小值)时要考虑哪个值:

    def find_winner(results):
        return max(results, key=lambda x: x[-1])
    

    输出

    print(find_winner(results_2002)) # ('Jim Newsom', 'Canada', 6.1)
    print(find_winner(results_2004)) # ('Simon Dent', 'Canada', 6.2)
    

    【讨论】:

      【解决方案3】:

      试试这个:

      results_2002 = [("John Williams", "USA", 5.5),("Jim Newsom",
      "Canada", 6.1), ("Paul Smith", "Netherlands", 5.3)]
      
      results_2004 = [("Simon Dent", "Canada", 6.2),("Stan Doe", "USA",
      6.1), ("Paul Smith", "Netherlands", 5.4)]
      
      def find_winner(results):
      
          return [j for j in results if j[2] == max([i[2] for i in results])] 
      
      print(*find_winner(results_2002))
      print(*find_winner(results_2004))
      

      输出:

      C:\Users\Documents>py test.py
      ('Jim Newsom', 'Canada', 6.1)
      ('Simon Dent', 'Canada', 6.2)
      

      注意:如果您希望将max 更改为@987654324,我将最大 作为获胜者 @。

      【讨论】:

        猜你喜欢
        • 2015-11-02
        • 1970-01-01
        • 1970-01-01
        • 2013-03-08
        • 1970-01-01
        • 1970-01-01
        • 2021-08-04
        • 2016-10-13
        • 2021-11-24
        相关资源
        最近更新 更多