我有源源不断的值流进来,有数百万条记录。 随着数字不断输入,我需要找到迄今为止实时到达的最小值和最大值。整个数据数组不可用。到达的数据不会被存储。
我尝试过类似的方法,但效果并不完美。有没有更好的方法使用库来解决这些问题,
numpy
,scipy
?
import numpy as np
rng = np.random.default_rng()
test = rng.choice(np.arange(-100,100, dtype=int), 10, replace=False)
testmax = 0
testmin = 0
for i in test: #simulates a stream
if i < testmax:
testmin = i
if i > testmax:
testmax = i
if i < testmin:
testmin = i
print (test, 'min: ',testmin, 'max: ', testmax)
>>> print (test, 'min: ',testmin, 'max: ', testmax)
[ 39 -32 61 -18 -53 -57 -69 98 -88 -47] min: -47 max: 98 #should be -88 and 98
>>>
>>> print (test, 'min: ',testmin, 'max: ', testmax)
[-65 -53 1 2 26 -62 82 70 39 -44] min: -44 max: 82 #should be -65 and 82
>>>
评论中指出了错误,但实际上只需要两次比较(可以使用python中的三元运算符来完成)。您还应该将 max 初始化为可能的最小值,将 min 初始化为可能的最大值。
import numpy as np
rng = np.random.default_rng(42)
test = rng.choice(np.arange(-100,100, dtype=int), 10, replace=False)
testmax = -100
testmin = 100
# simulates a stream
for i in test:
testmax = i if i > testmax else testmax
testmin = i if i < testmin else testmin
print (test, 'min: ',testmin, 'max: ', testmax)
# [-84 48 -83 26 -15 -16 38 -82 -60 68] min: -84 max: 68