python - 从嵌套列表中打印出最高价值的项目
问题描述
代码需要打印出为商店赚到最多钱的狗的品种。我知道我需要将数量 (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 结束
解决方案
使用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])
推荐阅读
- sql - 在 Postgresql 过程中创建和运行查询
- php - Roundcube 邮箱不是有效的 mbox 文件
- python - 如何在python中读取所有zipfile
- c# - 动态添加的控件未显示在 wpf 页面中
- java - 使用 Spring Data JPA 时如何处理 ObjectOptimisticLockingFailureException 和 StaleObjectStateException?
- javascript - 为什么这个 js 文件中有类型,为什么它在 react js 应用程序中有效,但在 react ts 应用程序中无效?
- wordpress - 带有我自己的主题的 Elementor Pro 主题构建器不能一起工作
- java - 使用 Spring JPA/Hibernate 按不同值批量更新
- swift - 更新到 Xcode 12 beta 6 后解析服务器不兼容的指针错误
- c# - System.Net.Mail.SmtpClient.Send 在本地主机上成功但在服务器上失败