簡體   English   中英

如何在字典中的每個條目插入一個新行?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM