基本字典脚本

时间:2018-08-17 07:38:38

标签: python python-3.x

我想制作一个程序,将清单作为字典数据,并在其底部打印出来。

# 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”调用该函数

2 个答案:

答案 0 :(得分:2)

您可以使用字符串格式,代码看起来更优雅,更多细节在这里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))

答案 1 :(得分:0)

array_1