首页 > 解决方案 > 从嵌套列表中打印出最高价值的项目

问题描述

代码需要打印出为商店赚到最多钱的狗的品种。我知道我需要将数量 (item[2]) 和金钱 (item[3]) 相乘以找出每只狗首先在商店中赚了多少钱,但我不知道如何让系统打印出最畅销的狗。它必须在 def 函数中解决,有谁知道我能做些什么来解决这个问题,谢谢!

# List of transactions [[breed, Dogname, quantity bought, price, age of dog]]
lst_dogs = [
    ["Pitbull", "Rover", 2, 90, 5],
    ["Greyhound", "Jess", 1, 100, 6],
    ["Lab", "Rose", 1,85, 3],
    ["Pitbull", "Daisy", 1, 90, 3],
]

def best_dog():
    sum = 0

    for i in range(len(lst_dogs)):

        item = lst_dogs[i]

        for item in lst_dogs:
            amount = item[2]
            price = item[3]
            total = amount * price
            sum += total

print("The dog which has earned the most money for the shop is", item[0])

期望的输出:为商店赚到最多钱的狗是:比特犬

实际输出:进程以退出代码 0 结束

标签: pythonprintingcalculatornested-listspython-3.9

解决方案


使用max按键功能:

lst_dogs = [
    ["Pitbull", "Rover", 2, 90, 5],
    ["Greyhound", "Jess", 1, 100, 6],
    ["Lab", "Rose", 1,85, 3],
    ["Pitbull", "Daisy", 1, 90, 3],
]

best_dog = max(lst_dogs, key=lambda item: item[2] * item[3])

print("The dog which has earned the most money for the shop is", best_dog[0])

推荐阅读