[英]Python sorted dict in formatting expression
我有這個格式的表達:
def __str__(self):
result = "\n".join({("{}: {}").format(key, self.__dict__[key]) for key, value in sorted(self.__dict__.items())})
return result
該代碼運行,但未排序。 我不明白為什么它沒有被排序。 每次以不同順序返回以下代碼。
currentPL: -438.627395715
portfolio: Balance: 10101
Transactions: 10
exitPrice: 1.14686
exitTime: 2017-07-12 06:0
entryTime: 2017-07-12 06:
currentlyOpen: True
entryPrice: 1.14686
direction: Long
currentPrice: 1.14188
transactionPL: 627.994644
currentPL100: -0.00434229
units: 88077.79030439684
portfolio: Balance: 10101
Transactions: 10
currentPrice: 1.14228
exitTime: 2017-07-12 06:0
entryTime: 2017-07-12 06:
currentlyOpen: True
entryPrice: 1.14686
direction: Long
transactionPL: 627.994644
currentPL100: -0.00399351
currentPL: -403.396279594
exitPrice: 1.14686
units: 88077.79030439684
...
您在一個集合(無序類型)上調用'\\n'.join
,這首先破壞了排序的'\\n'.join
:
您可以使用列表(序列):
"\n".join([...])
或刪除它們並直接使用生成器表達式。 這是一個使用itertools.starmap
易於閱讀的版本:
from itertools import starmap
result = "\n".join(starmap("{}: {}".format, sorted(self.__dict__.items()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.