我正在使用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)
我一直在尝试对元组进行反向排序,并打印出由此给出的第一个赛车手,但是我遇到了错误,或者它只会列出第一次放入列表中的赛车手。
答案 0 :(得分: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)
输出:
[('Paul Smith','Netherlands',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)
答案 1 :(得分:0)
尝试一下:
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
的最小变化作为目标,我将 maximum 作为 winner min
。
答案 2 :(得分:0)