首页 > 解决方案 > 如何在条件语句中使用嵌套在列表中的字典键值对的值?

问题描述

我搜索了很多关于堆栈溢出的类似帖子,但我找不到任何与我的特定问题相近的东西,如果之前有人问过并回答过,请提前原谅我。

我 5 天前开始学习 Python 编程,现在我正在尝试制作一个进行盲选的特定程序。我接受输入 - 名称和出价金额并将它们作为字典存储在列表中。多个这样的输入会导致一个列表,其中嵌套了很多字典。我定义了一个函数,它遍历最终字典列表中的不同输入并找出最高出价。

根据我的理解并在这篇文章中确认,我需要首先在第一个方括号中索引正确的元素,然后在下一个方括号中指向所需的键。

我已经在我的代码中实现了这一点,但我还是得到了这个特殊的错误。

```Traceback (most recent call last):
    File "main.py", line 36, in <module>
      blind_auction_result()
    File "main.py", line 14, in blind_auction_result
      if (total_bids[bidder]["amount"]) > max_bid:
TypeError: list indices must be integers or slices, not dict```

我使用的代码如下:

from replit import clear
from art import logo
total_bids = []
auction_active = True
def blind_auction_input(name,bid):
    auction_bids = {}
    auction_bids = {"name": name, "amount": bid}
    total_bids.append(auction_bids)
    print(total_bids)
def blind_auction_result():
    max_bid = 0
    bid_index = 0
    for bidder in total_bids:
        if (total_bids[bidder]["amount"]) > max_bid:
            max_bid = total_bids[bidder]["amount"]
            bid_index = bidder
    # print(f"The winner of this auction is {total_bids[bid_index]["name"]} who bid {total_bids[bid_index]["amount"]} $")
print(logo)
print("Welcome to todays' blind auction !")
while auction_active:
    bidder_name = input("What is your name?\n").lower()
    bid_amount = round(int(input("How much is your bid?\n")),2)
    while type(bid_amount) != int:
        bid_amount = round(int(input("Invalid input. Please enter a valid number.\n")),2)
    blind_auction_input(bidder_name,bid_amount)
    user_choice = input("Are there more bidders? Y or N.\n").lower()
    while not user_choice == "y" and not user_choice == "n":
        user_choice = input("Invalid input. Try again. Are there more bidders? Y or N.\n").lower()
    if user_choice == "y":
        auction_active = True
        clear()
    elif user_choice == "n":
        break
blind_auction_result()

另外,有一行我已经注释掉了,因为显然这也显示了一个错误,我只有在注释掉它之后才能运行它。我对如何解决这个特殊情况一无所知,非常感谢一些帮助:)

标签: pythonlistdictionarynestedconditional-statements

解决方案


只需将该循环更改blind_auction_result

    for bidder in total_bids:
        if bidder["amount"] > max_bid:
            max_bid = bidder["amount"]

for bidder in total_bids意味着您正在遍历列表项并在每个步骤中使用每个项。因此无需再次获取它们。


推荐阅读