创建最佳数据结构python

2024-06-01 13:37:33 发布

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

我正在交叉引用两个共享6个公共字段的数据源。其思想是将文件1中的营销成本分解为文件2中的销售交易。我已经写了一个方法来从第一个文件构建一个数据结构,这样第二个文件就可以快速访问它,但对我来说这似乎不是pythonic。我有兴趣得到一些意见和意见,是否有人认为它可以写得更好。你知道吗

cost_matrix = {}
for line in marketing_costs:
    line_date_object = time.strptime(line['date'], "%d/%m/%Y")
    period = '%04d_%02d' % (line_date_object.tm_year, line_date_object.tm_mon)
    territory = line['territory'].lower()
    salesperson=line['salesperson'].lower()
    customer_type = line['customer_type'].lower()
    affiliate=line['affiliate'].lower()
    product_group = line['product_group'].lower()
    line_mktg_cost=line['mktg_cost']
    try:
        cost_matrix[period]
    except KeyError:
        cost_matrix[period]={}
    try:
        cost_matrix[period][territory]
    except KeyError:
        cost_matrix[period][territory]={}
    try:
        cost_matrix[period][territory][salesperson]
    except KeyError:
        cost_matrix[period][territory][salesperson]={}
    try:
        cost_matrix[period][territory][salesperson][customer_type]
    except KeyError:
        cost_matrix[period][territory][salesperson][customer_type]={}
    try:
        cost_matrix[period][territory][salesperson][customer_type][affiliate]
    except KeyError:
        cost_matrix[period][territory][salesperson][customer_type][affiliate]={}
    try:
        cost_matrix[period][territory][salesperson][customer_type][affiliate][product_group]
    except KeyError:
        cost_matrix[period][territory][salesperson][customer_type][affiliate][product_group]={}
        cost_matrix[period][territory][salesperson][customer_type][affiliate][product_group]['mktg_cost']=0
    cost_matrix[period][territory][salesperson][customer_type][affiliate][product_group]['mktg_cost']+=Decimal(line_mktg_cost)

Tags: typelinegroupcustomerproductlowermatrixperiod
1条回答
网友
1楼 · 发布于 2024-06-01 13:37:33

这些4行try/except块中的每一个都可以使用^{}替换为1行:

setdefault(key[, default])

  • If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

因此:

cost_matrix[period].setdefault(territory, {})

…相当于:

try:
    cost_matrix[period][territory]
except KeyError:
    cost_matrix[period][territory]={}

但是你可以用一个更大的表达式,这意味着理论上你可以把整个事情变成一个巨大的表达式,如果你想的话,尽管我不确定我会这么做。你知道吗


通过使用递归^{},您可以进一步简化事情。一个defaultdict基本上只是一个dict,它通过自动设置默认值来处理丢失的键,递归的一个用另一个defaultdict而不是普通的dict来处理。(您仍然需要一个setdefault或只在末尾指定一个普通键来处理0的默认值,而不是另一个dict…)

像这样:

_make_defaultdict = lambda: defaultdict(_make_defaultdict)
recursive_defaultdict = defaultdict(_make_defaultdict)

cost_matrix = recursive_defaultdict()
cost_matrix[period][territory][salesperson][customer_type][
    affiliate][product_group]['mktg_cost'] = 0
cost_matrix[period][territory][salesperson][customer_type][
    affiliate][product_group]['mktg_cost'] += Decimal(line_mktg_cost)

但是,请注意,这意味着您也永远不会在代码的其他任何地方得到KeyError。如果不能接受,那就坚持使用setdefault。(虽然如果你基本上是在构建dict,那么使用它,你可以通过递归地复制它将它“冻结”成一个普通的dict

相关问题 更多 >