【发布时间】:2017-06-13 17:45:18
【问题描述】:
这当然很简单,但现在我已经尝试了几个小时来解决这个问题。 我想根据 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
我得到的输出如下所示:
[[ 157.]
[ 3.]
[ 6.]
[ 6.]
[ 5.]
[ 9.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]]
输入是:
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)
我非常感谢您对此提供一些指导。 谢谢!
【问题讨论】:
-
什么是“矩阵”? (Python 中没有这种数据类型。)
-
请显示您的代码 :) 您的问题表明您有一些代码,但可能错误地实际上并未包含您的代码。您打算仅在 第一个 实例中插入,还是在
val > element的所有 实例中插入? -
年,我只需要更换操作系统。我希望我的编辑能胜任大卫的工作。如果我需要详细解释任何事情,请告诉我。如您所见,第三列中的每个数字在第一列和第二列中都有一个所属值。它们还应该与存储值放在相同的索引处。我只是认为在三个向量中进行操作会更容易,然后在最后将它们组合起来。
-
@DYZ 矩阵我的意思是一个多维的numpy数组,这样更令人满意吗?
-
你试过numpy.insert功能吗?
标签: python loops matrix iteration vectorization