我正在交叉引用两个共享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)
这些4行} 替换为1行:
try
/except
块中的每一个都可以使用^{因此:
…相当于:
但是你可以用一个更大的表达式,这意味着理论上你可以把整个事情变成一个巨大的表达式,如果你想的话,尽管我不确定我会这么做。你知道吗
通过使用递归^{} ,您可以进一步简化事情。一个
defaultdict
基本上只是一个dict
,它通过自动设置默认值来处理丢失的键,递归的一个用另一个defaultdict
而不是普通的dict
来处理。(您仍然需要一个setdefault
或只在末尾指定一个普通键来处理0
的默认值,而不是另一个dict…)像这样:
但是,请注意,这意味着您也永远不会在代码的其他任何地方得到
KeyError
。如果不能接受,那就坚持使用setdefault
。(虽然如果你基本上是在构建dict,那么使用它,你可以通过递归地复制它将它“冻结”成一个普通的dict
)相关问题 更多 >
编程相关推荐