【发布时间】:2018-04-11 19:23:30
【问题描述】:
我的输入数据是一个 dicts 列表 (matches),其中每个 dict 有 2 个可能的位置来显示记录,以及两者及其各自数据源之间的相关因素:
[
{ 'r1': record_1, 'r2': record_2, corr: 85, 'r1_source': source_1, 'r2_source': source_2 },
{ 'r1': record_1, 'r2': record_3, corr: 90, 'r1_source': source_1, 'r2_source': source_3 },
{ 'r1': record_2, 'r2': record_3, corr: 77, 'r1_source': source_2, 'r2_source': source_3 },
...
]
每个record 都由一个列表表示,该列表来自唯一records 的有限列表。
我想要的输出数据的结构是一个字典列表,其中每个唯一的record 都有自己、它的来源和它的平均相关因子:
[
{ 'record': record_1, 'source': source_1, 'avg': (85 + 90) / 2 },
{ 'record': record_2, 'source': source_2, 'avg': (85 + 77) / 2 },
{ 'record': record_3, 'source': source_3, 'avg': (90 + 77) / 2 },
]
我目前的解决方案:
def average_record_from_match_value(matches):
averaged_recs = []
for match in matches:
# Q1
if [rec for rec in averaged_recs if rec['record'] == match['r1']] == []:
a_recs = []
# Q2
a_recs.extend([m['corr'] for m in matches if m['r1'] == match['r1']])
a_recs.extend([m['corr'] for m in matches if m['r2'] == match['r1']])
# Q3
r1_value = sum(a_recs) / len(a_recs)
averaged_recs.append({ 'record': match['r1'],
'source': match['r1_source'],
'match_value': r1_value,
'record_value': r1_value})
if [rec for rec in averaged_recs if rec['record'] == match['r2']] == []:
b_recs = []
b_recs.extend([m['corr'] for m in matches if m['r1'] == match['r2']])
b_recs.extend([m['corr'] for m in matches if m['r2'] == match['r2']])
r2_value = sum(b_recs) / len(b_recs)
averaged_recs.append({ 'record': match['r2'],
'source': match['r2_source'],
'match_value': r2_value,
'record_value': r2_value})
return averaged_recs
这可行,但我确信它可以改进。上面 cmets 标记的我的问题是:
- 这里有没有更好的方法来强制唯一性?我有胆量
感觉我不需要遍历我的
averaged_recs列表 每场比赛。 - 我可以在不循环的情况下将所有这些
records围起来吗 像这样超过他们两次? - 可以/应该将此平均计算与之前的列表扩展结合起来吗?
感谢您的帮助!
【问题讨论】:
标签: python dictionary list-comprehension