繁体   English   中英

根据列表中的属性将python列表排序为列表字典

[英]Sort python list into dictionary of lists, based on property in list

我正在尝试通过原始列表中对象的属性将python中的对象列表排序为列表字典

我已经在下面完成了,但这听起来像我应该能够使用字典理解来完成?

for position in totals["positions"]:
        if not hasattr(totals["positions_dict"], position.get_asset_type_display()):
            totals["positions_dict"][position.get_asset_type_display()] = []
        totals["positions_dict"][position.get_asset_type_display()].append(position)

一些自我改进

totals["positions_dict"] = {}
    for position in totals["positions"]:
        key = position.get_asset_type_display()
        if key not in totals["positions_dict"]:
            totals["positions_dict"][key] = []
        totals["positions_dict"][key].append(position)

您可以在dict理解中使用itertools.groupbyoperator.methodcaller

from operator import methodcaller
from itertools import groupby

key = methodcaller('get_asset_type_display')
totals["positions_dict"] = {k: list(g) for k, g in groupby(sorted(totals["positions"], key=key), key=key)}

使用@Jean-FrançoisFabre建议的defaultdict可以让您在一个循环中通过一次调用get_asset_type_display()来做到这一点:

from collections import defaultdict

totals["positions_dict"] = defaultdict(list)
for position in totals["positions"]:
    totals["positions_dict"][position.get_asset_type_display()].append(position)

尚未测试,因为我没有您的数据。 而且我认为这很丑陋,但可能会起作用:

totals ['positions_dict'] = {
    key: [
        position
        for position in totals ['positions']
        if position.get_asset_type_display () == key
    ]
    for key in {
        position.get_asset_type_display ()
        for position in totals ['positions']
    }
}

但我希望使用一些非常简单的方法,并避免不必要的查找/调用:

positions = totals ['positions']
positions_dict = {}

for position in positions:
    key = position.get_asset_type_display ()
    if key in positions_dict:
        positions_dict [key] .append (position)
    else:
        positions_dict [key] = [position]


totals ['positions_dict'] = positions_dict
positions = totals ['positions']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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