我有一本字典,我想用一种特定的格式显示它。
这是我的字典:
tree = {
'wesley': {
'1': {
'romulan': {
'1': '0',
'0': '1'
}
},
'0': {
'romulan': {
'1': '0',
'0': {
'poetry': {
'1': {
'honor': {
'1': '0',
'0': '1'
}
},
'0': {
'honor': {
'1': '1',
'0': '0'
}
}
}
}
}
}
}
}我想把它展示为:
wesley = 1 :
| romulan = 1 : 0
| romulan = 0 : 1
wesley = 0 :
| romulan = 1 : 0
| romulan = 0 :
| | poetry = 1 :
| | | honor = 1 : 0
| | | honor = 0 : 1
| | poetry = 0:
| | | honor = 1 : 1
| | | honor = 0 : 0我对字典和Python非常陌生,我对如何显示它们一无所知。
发布于 2016-09-23 03:05:33
这将使它在没有递归的情况下非常接近,尽管它可能很脆弱。
import json
tree = {'wesley': {'1': {'romulan': {'1': '0', '0': '1'}}, '0': {'romulan': {'1': '0', '0': {'poetry': {'1': {'honor': {'1': '0', '0': '1'}}, '0': {'honor': {'1': '1', '0': '0'}}}}}}}}
tree_str = json.dumps(tree, indent=4)
tree_str = tree_str.replace("\n ", "\n")
tree_str = tree_str.replace('"', "")
tree_str = tree_str.replace(',', "")
tree_str = tree_str.replace("{", "")
tree_str = tree_str.replace("}", "")
tree_str = tree_str.replace(" ", " | ")
tree_str = tree_str.replace(" ", " ")
print(tree_str)输出:
(.venv35) ➜ stackoverflow python weird_formated_print.py
wesley:
| 0:
| | romulan:
| | | 0:
| | | | poetry:
| | | | | 0:
| | | | | | honor:
| | | | | | | 0: 0
| | | | | | | 1: 1
| | | | | |
| | | | |
| | | | | 1:
| | | | | | honor:
| | | | | | | 0: 1
| | | | | | | 1: 0
| | | | | |
| | | | |
| | | |
| | |
| | | 1: 0
| |
|
| 1:
| | romulan:
| | | 0: 1
| | | 1: 0
| |
|您可以在.replace()调用中四处游玩,以得到正确的结果。
发布于 2016-09-23 04:00:22
这将完全输出您想要的结果。
# If you are not using Python 3
from __future__ import print_function
tree = {'wesley': {'1': {'romulan': {'1': '0', '0': '1'}}, '0': {'romulan': {'1': '0', '0': {'poetry': {'1': {'honor': {'1': '0', '0': '1'}}, '0': {'honor': {'1': '1', '0': '0'}}}}}}}}
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def go(dic, last_key, current_level):
for key, value in dic.items():
if is_number(key):
for i in range(current_level - 1):
print("| ", end="")
print(last_key, "= ", end="")
print(key, ": ", end="")
else:
if current_level > 0:
print("")
current_level = current_level + 1
if isinstance(value, dict):
go(value, key, current_level)
else:
print(value)
go(tree, None, 0)输出:
wesley = 1 :
| romulan = 1 : 0
| romulan = 0 : 1
wesley = 0 :
| romulan = 1 : 0
| romulan = 0 :
| | poetry = 1 :
| | | honor = 1 : 0
| | | honor = 0 : 1
| | poetry = 0 :
| | | honor = 1 : 1
| | | honor = 0 : 0https://stackoverflow.com/questions/39651638
复制相似问题