我的目标是在一个列表中找到几个(在本例中=3)最大值,fourire
,识别列表中的位置,并在另一个列表中获取相应的(position_wise)值, freq
,所以打印输出应该像
2。 27.
9。 25.
4。 22.
附加的Python工作正常......有点。
** 请注意,我正在处理 numpy 数组,因此 index() 不起作用......
有什么办法可以改善以下问题吗?
import heapq
freq = [ 2., 8., 1., 6., 9., 3., 6., 9., 4., 8., 12.]
fourire = [ 27., 3., 2., 7., 4., 9., 10., 25., 22., 5., 3.]
out = heapq.nlargest(3, enumerate(fourire), key=lambda x:x[1])
elem_fourire = []
elem_freq = []
for i in range(len(out)):
(key, value) = out[i]
elem_freq.extend([freq[key]])
elem_fourire.extend([value])
for i in range(len(out)):
print elem_freq[i], elem_fourire[i]
最佳答案
import numpy as np
fourire = np.array(fourire)
freq = np.array(freq)
ix = fourire.argsort(kind='heapsort')[-3:][::-1]
for a, b in zip(freq[ix],fourire[ix]):
print a, b
打印
2.0 27.0
9.0 25.0
4.0 22.0
如果您想使用 heapq 而不是 numpy,只需对上面的代码稍作修改即可:
ix = heapq.nlargest(3,range(len(freq)),key=lambda x: fourire[x])
for x in ix:
print freq[x], fourire[x]
结果相同
关于python - 优化与 heapq.nlargest 相关的 python 文件并使用循环扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16070216/