python - 优化与 heapq.nlargest 相关的 python 文件并使用循环扩展

标签 python numpy extend

我的目标是在一个列表中找到几个(在本例中=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/

相关文章:

python - 我应该如何使用 python 和 BS4 从网页中正确提取和解析主题数据?

python - 在 Django 中引用我的(可重用)应用程序的 url 命名空间

numpy - Lua Torch 相当于 np.where()?

javascript - 灰尘模板包含多次

javascript - 在Javascript中扩展继承的原型(prototype)方法

python - 将 ctypes 指针转换为 float 的 numpy 数组

python - 具有给定精度的 float 范围

python-3.x - Numpy , Python3.6 - 无法理解为什么地址不同?

jquery - jquery扩展的两种方式有什么不同?

python - Python 为对象引用打印 "[...]"是什么意思?