[英]How do i insert a new line after every dictionary key pair print using dictionary comprehension as done by the pprint function in Python?
[英]How to insert a new line every entry in a dictionary?
def __repr__(self):
'shows all city attributes'
return str(self.__dict__).strip('{}').replace("'", "")
我在我的課上有這個返回:
name: Jerusalem, center: (31, 35), central_station: (19.7, 25.22), num_residents: 900000, num_neighborhoods: 58
如何將其更改為(新行中的每個細節):
name: Jerusalem
center:(9, 20)
...
...
實際上我還有另一個問題——有沒有更好的方法來做這個清單?
您可以遍歷定義,並將格式應用於每個項目,就像這樣......
class Foo:
def __repr__(self):
'''shows all city attributes'''
line_format = '%s : %s'
return "\n".join([line_format % (key, str(value)) for key, value in self.__dict__.items()])
用法看起來像這樣......
a = Foo()
a.a = "Hello"
a.b = "World"
a.c = (1, 2, 3)
print(a)
a : Hello b : World c : (1, 2, 3)
現在,如果您想更改演示文稿的格式,您只需將line_format
更改為"%s -> %s"
或其他顯示數據的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.