我想制作一个程序,将清单作为字典数据,并在底部打印总数。
# inventory.py
stuff = {"coal":42,"dagger":1,"iron":
20,"torch":2}
total_items = 0
def display_inventory(inventory):
for k,v in inventory.items():
print(k,v)
global total_items
total_items = total_items + v
print("\n")
print("Total: " + str(total_items))
我想在输出中添加冒号,例如:
煤:42
匕首:2
我该怎么做呢?
编辑:我们使用变量“ stuff”来调用函数
最佳答案
您可以使用字符串格式,代码看起来优雅,更多细节在这里https://www.programiz.com/python-programming/methods/string/format
# inventory.py
stuff = {"coal":42,"dagger":1,"iron":
20,"torch":2}
total_items = 0
def display_inventory(inventory):
for k,v in inventory.items():
print("{}:{}".format(k,v))
global total_items
total_items = total_items + v
print("\n")
print("Total: " + str(total_items))
关于python - 基本字典脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51890512/