目前,我正在尝试检查项目字典并通过它们检查值。如果该值大于 0,则将其打印在列表中,否则将其忽略并继续。目前我已经输入了以下代码:
from items import items
for item in items:
if items[item][6] < 0:
print("You have ", item[6], " of ", item[0], " .")
但是从这里开始我对如何继续这件事感到非常困惑。我收到索引错误,但我不确定它的用途。
最佳答案
您正在迭代一个字典,其中键是项目的名称,值是一个包含一些信息的元组。
您可以这样做注意,只有当您的元组始终具有相同的结构/字段数量时,这才有效。
In [23]: my_items = {'Broken Watch': ('Broken Watch', 'This is a watch. It appears to be shattered, and the hands are no longer moving.', 'Item', 'Junk', 1, 1, 0), 'Watch that will
...: print': ('Some stuff', 'More stuff', 'Item', 'Junk', 1, 1, 7)}
In [24]: for name, info in my_items.items():
...: num= info[6]
...: print("Checking num", num)
...: if num > 0:
...: print("You have", num, "of", name, ".")
...:
...:
...:
Checking num 0
Checking num 7
You have 7 of Watch that will print .
关于python - 如何从字典中打印具有特定键的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57239076/