我写了几行代码来解决这个问题,但是分析器说,这非常耗时。 (使用 kernprof 逐行分析器) 这是代码:
comp = [1, 2, 3] #comp is list with always 3 elements, values 1, 2, 3 are just for illustration
m = max(comp)
max_where = [i for i, j in enumerate(comp) if j == m]
if 0 in max_where:
some action1
if 1 in max_where:
some action2
if 2 in max_where:
some action3
Profiler 说大部分时间都花在了 max_where 计算上。我也尝试过将这个计算拆分成if-tree来避免一些不必要的操作,但结果并不令人满意。
拜托,我做错了吗还是只是python?
请您参考如下方法:
如果它总是三个元素,为什么不简单地做:
comp = [1, 2, 3]
m = max(comp)
if comp[0] == m:
some action
if comp[1] == m:
some action
if comp[2] == m:
some action
