繁体   English   中英

Python在格式化表达式中排序字典

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM