我刚刚开始学习python,我正在构建一个文本游戏.我想要一个库存系统,但我似乎无法打印出字典而不看起来很难看.这是我到目前为止:
def inventory():
for numberofitems in len(inventory_content.keys()):
inventory_things = list(inventory_content.keys())
inventory_amounts = list(inventory_content.values())
print(inventory_things[numberofitems])
Run Code Online (Sandbox Code Playgroud)
谢谢!
fos*_*ock 41
我喜欢pprintPython中包含的模块.它可用于打印对象,或格式化它的漂亮字符串版本.
import pprint
# Prints the nicely formatted dictionary
pprint.pprint(dictionary)
# Sets 'pretty_dict_str' to
pretty_dict_str = pprint.pformat(dictionary)
Run Code Online (Sandbox Code Playgroud)
但这听起来像是在打印出一个库存,用户可能希望将其显示为更像以下内容:
def print_inventory(dct):
print("Items held:")
for item, amount in dct.items(): # dct.iteritems() in Python 2
print("{} ({})".format(item, amount))
inventory = {
"shovels": 3,
"sticks": 2,
"dogs": 1,
}
print_inventory(inventory)
Run Code Online (Sandbox Code Playgroud)
打印:
Items held:
shovels (3)
sticks (2)
dogs (1)
Run Code Online (Sandbox Code Playgroud)
Ofe*_*dan 23
我最喜欢的方式:
import json
print(json.dumps(dictionary, indent=4, sort_keys=True))
Run Code Online (Sandbox Code Playgroud)
这是我要用的一线纸。(编辑:也适用于无法JSON序列化的内容)
print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))
Run Code Online (Sandbox Code Playgroud)
说明:这将遍历字典的键和值,为每个键和键创建一个格式化的字符串,例如key + tab + value。并"\n".join(...在所有这些字符串之间放置换行符,形成一个新字符串。
例:
>>> dictionary = {1: 2, 4: 5, "foo": "bar"}
>>> print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))
1 2
4 5
foo bar
>>>
Run Code Online (Sandbox Code Playgroud)
我建议使用beeprint而不是 pprint。
例子:
打印
{'entities': {'hashtags': [],
'urls': [{'display_url': 'github.com/panyanyany/beeprint',
'indices': [107, 126],
'url': 'https://github.com/panyanyany/beeprint'}],
'user_mentions': []}}
Run Code Online (Sandbox Code Playgroud)
蜂印
{
'entities': {
'hashtags': [],
'urls': [
{
'display_url': 'github.com/panyanyany/beeprint',
'indices': [107, 126],
'url': 'https://github.com/panyanyany/beeprint'}],
},
],
'user_mentions': [],
},
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43275 次 |
| 最近记录: |