如何优化大型列表聚合

时间:2019-04-12 02:50:25

标签: algorithm loops aggregation

我想根据排名汇总项目得分
项目将显示在不同的列表上。该列表是等级。 根据不同列表中的项目位置获得不同的分数。然后将所有分数相加

当rank_items列表很大时,例如1000(list)* 1000(items),则循环将花费很长时间。 有没有解决这个问题的方法

我已经尝试优化python。以下是一个简单的版本,易于理解

我希望有另外一种解决方法可以跳出框框。使用不同的方法来解决这个问题

'''
there are some list of ranked items
each list has a,b,c,d on different rank
'''
ranked_items = [
  ['a','b','c','d'],
  ['b','c','a','d'],
  ['d','c','b','a']
]

'''
base on item location in the list
the first location has score 0.9
the second location has score 0.7
'''
base_score = {
  0:0.9,
  1:0.7,
  2:0.5,
  3:0.3
}

'''
sum total score of each item
eg: 'a' in the first list first location then score is 0.9
in the second list third location then score is 0.5
the third list last location then score is 0.3
add them all.'a' final score is 1.7
'''
final_score = {}
for single_rank in ranked_items:
  for idx,item in enumerate(single_rank):
    final_score[item] = final_score.get(item,0) + base_score[idx]

#sort by score
final_score_sorted = sorted(final_score.items(),key=lambda kv: kv[1],reverse=True)

print(final_score_sorted)

'''
output
[('b', 2.1), ('c', 1.9), ('a', 1.7), ('d', 1.5)]
'''

和rank_items可以使用其他格式
这是一维列表格式的例子

ranked_items = [
    ('a',0),
    ('b',1),
    ('c',2),
    ('d',3),

    ('b',0),
    ('c',1),
    ('a',2),
    ('d',3),

    ('d',0),
    ('c',1),
    ('b',2),
    ('a',3)
]

1 个答案:

答案 0 :(得分:0)

如果rank_items作为2D列表提供,那么您就无济于事,无法提高运行时的复杂性,因为您必须至少浏览一次2D列表才能读取数据。

意味着,根据我的拙见,最好的可想象复杂度是O(N ^ 2)(给定N = len([a,b,c,d]))。

对于显示的一维变量, 您会发现,要产生任何一种结果,必须至少读取一次整个列表。我们将一维列表的长度称为M。因此,可以想到的最佳复杂度是O(M)。

请注意,这对最后一种方法没有任何改进,因为M = N ^ 2,其中N是2D表示形式中子列表的长度。 因此,O(M)= O(N ^ 2)。你做不到这件事。

相关问题