在for循环Python中查找前10个最大值

时间:2018-10-01 16:40:39

标签: python for-loop max

我试图在for循环中找到前10/300个值。我知道如何找到整个循环的最大值,但是我试图计算300个值,然后仅使用这300个值中的前10个值。

这是我的for循环:

random.shuffle(folder)
for i in range(len(folder)):
if i < 30:
    phaseresult_i = []
    data = np.loadtxt(dir + folder[i])
    time = data[:,0]-2450000
    magnitude = data[:,1]
    #print ('\n File:', folder[i],'\n','Time:',time,'\n', 'Magnitude:', magnitude)
    t = 10000 * time
    y = np.sin(2 * np.pi * t) * time
    frequency, power = LombScargle(t, y).autopower()
    period = np.log(1/frequency)[np.argmax(power)]
    maxpower = power.max()
    for t in range(len(time)):
        #print(t,time[t])
        floor = math.floor((time[t]-time[0])/period)
        phase_i = ((time[t]-time[0])/period)-floor
        phaseresult_i.append(phase_i)
    maxpower_i.append(maxpower)   
    folder_i.append(folder[i])
else: 
    break

我试图找到最大值的值是前十个最大幂及其周期。

2 个答案:

答案 0 :(得分:1)

出于演示目的,我重新排列了300个整数的列表,以获取10个最大值,您可以使用sorted然后采用范围[-10:]

import random

l = [*range(300)]
random.shuffle(l)

print(sorted(l)[-10:])
[290, 291, 292, 293, 294, 295, 296, 297, 298, 299]

更新

random.shuffle(folder)
for i in range(len(folder)):
  max_powers = []
  if i < 3:
    max_powers = []
    phaseresult_i = []
    data = np.loadtxt(dir + folder[i])
    time = data[:,0]-2450000
    magnitude = data[:,1]
    print ('\n File:', folder[i],'\n','Time:',time,'\n', 'Magnitude:', magnitude)
    t = 10000 * time
    y = np.sin(2 * np.pi * t) * time
    # Lomb Scargle Periodogram
    frequency, power = LombScargle(t, y).autopower()
    for period in folder[i]:
        period = np.log(1/frequency)[np.argmax(power)]
        maxpower = power.max()
    max_powers.append((maxpower, i))
    print('\n Max Power = ', maxpower)
    print('\n Period = ', period, '\n ---------------------------')
  print('\n Max Powers, Folder = {}'.format(sorted(max_powers, key=lambda x: x[0])[:-10]))
else:
    break

答案 1 :(得分:0)

您可以将heapq.nlargest与生成器一起使用,以给出可迭代对象的前10个值。这是一个简单的示例:

from random import sample
from heapq import nlargest

def gen(n):
    yield from sample(range(n), k=n)

res = nlargest(10, gen(100))

[99, 98, 97, 96, 95, 94, 93, 92, 91, 90]

您现在只需要将逻辑转换为生成器函数(请参见12)。