Python 巨蟒拍卖行计算获胜者

Python 巨蟒拍卖行计算获胜者,python,Python,大家好,我正在建立一个拍卖行为,出现了这个错误。如果最高出价[某人]>获胜者: TypeError:列表索引必须是整数或切片,而不是dict。 我尝试了几种方法,例如在compare()中添加列表,但仍然无法解决问题。我想让它看起来像谁出价最高,然后谁会在拍卖行中获胜,但是,当然,我会在那之后添加一些描述,但现在我的问题是,我无法使用compare()确定谁是赢家。如果您能帮助我完成我的小项目,我将不胜感激。我修复了您的代码 print("Welcome to the Auction

大家好,我正在建立一个拍卖行为,出现了这个错误。如果最高出价[某人]>获胜者:

TypeError:列表索引必须是整数或切片,而不是dict。

我尝试了几种方法,例如在compare()中添加列表,但仍然无法解决问题。我想让它看起来像谁出价最高,然后谁会在拍卖行中获胜,但是,当然,我会在那之后添加一些描述,但现在我的问题是,我无法使用compare()确定谁是赢家。如果您能帮助我完成我的小项目,我将不胜感激。

我修复了您的代码

print("Welcome to the Auction House")
name = input("Enter your name: ")
price = int(input("Enter your price: "))

total_list = []
def store_data(name, price):
    name_list = {}
    name_list["name"] = name
    name_list["price"] = price
    total_list.append(name_list)

def compare(highest_bid):
    winner = 0
    winn = ""
    for someone in highest_bid:
        if highest_bid[someone] > winner:
            winner = highest_bid["price"]
            winn = winner
    print(winn)

store_data(name, price)
something = True
while something:
    question = input("Is there other who want to bid? (y/n) ").lower()
    if question == "y":
        name = input("Enter your name: ")
        price = int(input("Enter your price: "))
        store_data(name, price)
    else:
        compare(total_list)
        something = False

问题在于比较功能。 我给你修一下

def compare(highest_bid):
    winner = 0
    winn = ""
    for someone in highest_bid:
        if someone["price"] > winner:
            winner = someone["price"]
            winn = someone["name"]
    print(winn)

您正在尝试访问字典,但total_list是一个列表。您可以根据需要不断更新名称列表

def compare(highest_bid):
    winner = 0
    winn = ""
    # for someone in highest_bid:
    #     if highest_bid[someone] > winner:
    #         winner = highest_bid["price"]
    #         winn = winner
    for someone in highest_bid:
        if someone["price"] > winner:
            winner = someone["price"]
            winn = winner
    print(winn)
然后在比较函数中使用键访问值

name_list = {}
def store_data(name, price):
    name_list.update({name : price})

在compare函数中传递name\u list。

您的函数
compare
需要一个字典(您正在尝试获取
“price”
项),但您传递的是一个列表
total\u list
,因此您得到了错误,这是否回答了您的问题?谢谢。很有效,谢谢。它起作用了。
def compare(highest_bid):
    winner = 0
    winn = ""
    for someone in highest_bid:
        if highest_bid.get(someone) > winner:
            winner = highest_bid.get(someone)
            winn = winner
    print(winn)