我以这个列表为例
favourite_candy_boys_girls = [['薯片', 1, 2], ['巧克力', 3, 4], [' Lollipop ', 2, 4]]
第二列指的是男孩,第三列指的是女孩。我想编写一个函数,返回女孩最喜欢的第一个糖果(在本例中应该是巧克力)。我知道如果我运行以下命令:
max(l[2] for l in favourite_candy_boys_girls)
我会找到最大值,但我不太确定如何归还糖果
编辑 我正在考虑使用循环将其编写为函数,如下所示:
>>> def get_candy_with_max_girls(Candy: SystemData):
"""Return the candy type that has the most girls.
If there is a tie of girls for a particular candy type, return the
candy type that appears first in candy.
>>> get_candy_with_max_girls(favourite_candy_boys_girls):
'Chocolate'
"""
最佳答案
您可以使用 max 函数的 key
参数。它允许您在对项目进行排序之前提供一个将在项目上使用的函数:
l = [['Chips' , 1, 2], ['Chocolate', 3, 4], ['Lollipops', 2, 4]]
max(l, key=lambda x: x[2])[0]
# returns 'Chocolate'
关于python - 返回第三列处具有最大值的子列表的第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059256/