这当然很简单,但现在我已经试着花了几个小时来思考这个问题。 我想对照10x1矩阵中的所有值来检查一个值,如果它大于它们中的任何一个,它应该插入大于的元素之前。在
到目前为止,我已经尝试了以下代码的不同变体,但是运气不佳。 我得出的结论如下:
我所做的:
col,col1,col2 = np.zeros((10,1)),np.zeros((10,1)),np.zeros((10,1))
for element in col:
if (aggdelay>element):
col[n,0] = aggdelay
col1[n,0] = flight_num
col2[n,0] = airline_id
break
n +=1
if (n>10):
n=0
我得到的输出如下所示:
^{pr2}$输入是:
19790 1256 124.0
19790 1257 157.0
19790 1258 3.0
19790 1264 6.0
19790 1266 6.0
19790 1280 5.0
19790 1282 9.0
预期产出为:
19790 1258 3.0
19790 1280 5.0
19790 1264 6.0
19790 1266 6.0
19790 1282 9.0
19790 1256 124.0
19790 1257 157.0
我实现了David提供的解决方案,但是我发现很难用新元素更新“矩阵”。 这是我目前的解决方案,但我怀疑它不能正确更新。在
#!/usr/bin/python
import sys
import collections
import numpy as np
from operator import itemgetter
result =np.zeros((3,1))
col,col1,col2 = []*10,[]*10,[]*10
col11,col12,col23 = [],[],[]
old_flight_num, old_airline_id = None, None
lines = sys.stdin.readlines()
sumDelay1, num = 0, 1
n = 0
for line in lines:
line, line = line.strip(), line.split("\t")
if len(line) !=3:
continue
airline_id, flight_num, aggdelay = line
try:
aggdelay = float(aggdelay)
flight_num= int(flight_num)
airline_id = int(airline_id)
except ValueError:
continue
if (old_airline_id is not None) and (old_airline_id != airline_id):
res2.sort(key=itemgetter(2))
print(' ')
print('Here come the results for airline ID: ', (old_airline_id))
print(' ')
for row in res2:
print(row)
col,col1,col2 = []*10,[]*10,[]*10
n=0
if (n<10):
col.append(airline_id),col1.append(flight_num),col2.append(aggdelay)
else:
res = zip(col,col1,col2)
res.sort(key=itemgetter(2))
if (aggdelay>min(col2)):
res.remove(res[0])
col11.append(airline_id), col12.append(flight_num), col23.append(aggdelay)
res1 = zip(col11,col12,col23)
res2=res+res1
res2.sort(key=itemgetter(2))
col11,col12,col23 = [],[],[]
n += 1
old_airline_id = airline_id
if (old_airline_id is not None):
res2.sort(key=itemgetter(2))
print(' ')
print('Here come the results for airline ID: ', (old_airline_id))
print(' ')
for row in res2:
print(row)
我非常感谢你对这一点的指导。 谢谢您!在
这也许能做到这一点,但我不得不猜测一下您对输出的期望以及如何处理输入(假设在3列中给出了Airline ID、flight number和delay)。在
这将给您一个包含3列的
ndarray
对象,第一列是您的“delay”,然后是航班号,然后是航空公司id,并按第一列进行排序。在如果您只对top-N感兴趣,那么只需使用上面的方法构建整个矩阵并将其切片:
^{pr2}$不使用
list.sort
方法和切片,您可以按相反的顺序对ndarray
对象进行排序:相关问题 更多 >
编程相关推荐