python - 返回第三列处具有最大值的子列表的第一项

标签 python list loops nested-loops

我以这个列表为例

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/

相关文章:

python - 在Python中平均分配和压缩两个不同长度的列表

list - 如何判断一个数字是否在斐波那契数列中

C++ 华氏度到摄氏度(反之亦然)循环问题

c++ - 程序无法编译

python - 为什么 "as"在 Jython 2.5 中的 "except"语句中导致 SyntaxError?

python - 类中派生类中预期方法的断言和文档

wordpress - 获取 WordPress 中排队脚本的列表?

python - 是否有一种 pythonic 方法来迭代范围字典以构建新字典?

python - SQLAlchemy - 将模型子类定义为表的子集

python - JSON 的结构化查询语言(在 Python 中)