python - 如何在条件语句中使用嵌套在列表中的字典键值对的值?
问题描述
我搜索了很多关于堆栈溢出的类似帖子,但我找不到任何与我的特定问题相近的东西,如果之前有人问过并回答过,请提前原谅我。
我 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()
另外,有一行我已经注释掉了,因为显然这也显示了一个错误,我只有在注释掉它之后才能运行它。我对如何解决这个特殊情况一无所知,非常感谢一些帮助:)
解决方案
只需将该循环更改blind_auction_result
为
for bidder in total_bids:
if bidder["amount"] > max_bid:
max_bid = bidder["amount"]
for bidder in total_bids
意味着您正在遍历列表项并在每个步骤中使用每个项。因此无需再次获取它们。
推荐阅读
- python - 在 Flask 中创建 Python 类的多个实例
- android - Android RotateDrawable:不适用于矢量可绘制对象
- swift - 快速,如何制作从 Firebase 返回查询快照的功能?
- parsing - 使用多个参数解析 - awk
- jquery - 在 Datatables 中排序时,相同数量的数据会使索引洗牌
- r - 基于温度阈值向量汇总温度数据
- javascript - 如何同步执行javascript函数
- facebook - Facebook 隐私政策(适用于不想使用用户登录的应用)
- operating-system - 在 MCU 上使用实时操作系统而不是 while-loop 的原因/好处
- sdk - MapBox SDK Xamarin - 建筑挤压