我有这个格式化表达式:
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([...])
或者删除它们并直接使用生成器表达式。这是一个非常可读的版本,使用 itertools.starmap
:
from itertools import starmap
result = "\n".join(starmap("{}: {}".format, sorted(self.__dict__.items()))
关于Python在格式化表达式中对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45062543/