格式化表达式中的Python排序dict

2024-09-28 01:30:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个格式化表达式:

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

...

Tags: keyselftrueresultdicttransactionsbalanceportfolio
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:11

您正在调用集合(无序类型)上的'\n'.join,这首先破坏了排序的最初目的:

可以使用列表(序列):

"\n".join([...])

或者删除它们并直接使用生成器表达式。下面是一个使用^{}的可读性很强的版本:

from itertools import starmap

result = "\n".join(starmap("{}: {}".format, sorted(self.__dict__.items())) 

相关问题 更多 >

    热门问题