优化python文件相关heapq.n最大并使用循环进行扩展

2024-10-04 03:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是在一个列表fourire中找到几个(=3)最大的值,确定列表中的位置,并在另一个列表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]

Tags: keyin目标列表forlenvaluerange
1条回答
网友
1楼 · 发布于 2024-10-04 03:27:51
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

印刷品

^{pr2}$

如果您想使用heapq而不是numpy,对上面的代码稍作修改就会得到:

ix = heapq.nlargest(3,range(len(freq)),key=lambda x: fourire[x])
for x in ix:
    print freq[x], fourire[x]

结果相同

相关问题 更多 >