You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python盲拍程序如何获取最高出价?解决max()函数报错问题

解决盲拍程序的最高出价获取问题

问题根源

你遇到的TypeError有三个核心原因:

  1. Python无法直接比较两个字典的大小,默认没有定义字典间的"大小"判断规则
  2. 代码里brandnew_user = {name: bid},的逗号导致每个出价字典被额外包在了元组里,数据结构多了一层不必要的嵌套
  3. 出价bid是字符串类型,就算能比较,也会按字符顺序而非数值大小判断,结果必然出错

修复步骤

  1. 修正数据结构:移除字典定义后的逗号,直接将字典存入data列表,取消元组嵌套
  2. 转换出价类型:将输入的出价转为整数(或浮点数),确保数值比较逻辑正确
  3. 正确使用max()函数:通过key参数指定比较规则,提取每个字典里的出价数值作为比较依据

修改后的完整代码

import os

data = []
while True:
    name = input("What is your name?: ")
    # 将出价转为整数,可额外添加输入异常处理(可选)
    bid = int(input("What is your bid: $"))

    other_user = input("Are there any other bidders? Type Yes or No.\n")
    
    if other_user.lower() == 'yes':
        os.system('cls')
 
    def new_user(name, bid):
        # 直接生成字典,不再嵌套元组
        brandnew_user = {name: bid}
        data.append(brandnew_user)
        
    new_user(name, bid)

    
    if other_user.lower() == 'no':
        # 用lambda提取每个字典的出价数值作为比较key
        highest_bid = max(data, key=lambda x: list(x.values())[0])
        # 解析获胜者信息
        winner_name = list(highest_bid.keys())[0]
        winner_bid = list(highest_bid.values())[0]
        print(f"The winner is {winner_name} with a bid of ${winner_bid}")
        break

额外优化建议

  • 把new_user函数移到循环外部,避免每次循环重复定义函数
  • 可添加输入验证逻辑,防止用户输入非数字的出价内容
  • 用other_user.lower()统一判断输入,无需同时处理大小写情况

内容的提问来源于stack exchange,提问作者DJ MASK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:27:27