我在spyder IDE中运行了以下代码:
idnum = 201034628
seed(idnum);
w = np.random.rand(200)
print(w)
这将产生以下结果:
[0.00176212 0.79092217 0.1759531 0.00239256 0.78842458 0.30404404
0.25633004 0.88271124 0.72031936 0.17356416 0.5674158 0.83897948
0.4133943 0.22471237 0.66562002 0.70207085 0.55722598 0.86308392
0.14584968 0.66224337 0.79900625 0.2687224 0.45508786 0.99014178
0.176943 0.42335567 0.41034833 0.75497287 0.41301282 0.11294302
0.58715198 0.01524138 0.58633177 0.9784454 0.14610789 0.68654175
0.94733177 0.93776749 0.17294272 0.7491281 0.94087871 0.60510781
0.43708462 0.77303273 0.13250525 0.50794632 0.36706808 0.46873059
0.99757662 0.144249 0.69427544 0.78359245 0.64836852 0.16574067
0.98633778 0.05613428 0.51713291 0.27246708 0.26216551 0.44605373
0.99963659 0.90569603 0.31139955 0.25559081 0.8295379 0.84638476
0.48194161 0.505123 0.57456517 0.62727722 0.11940848 0.49435157
0.07438197 0.11481526 0.74184931 0.94697125 0.93788422 0.3586455
0.852594 0.35167897 0.57139446 0.77923007 0.09070311 0.07821641
0.38140649 0.80945136 0.81820638 0.8140444 0.94458644 0.42983398
0.06609377 0.25737315 0.27873234 0.87183073 0.14317078 0.8964766
0.00731705 0.16095917 0.70980283 0.49757526 0.06990482 0.15304861
0.02710815 0.21319381 0.82069776 0.19839614 0.64250566 0.6383788
0.12539173 0.74583486 0.11041236 0.827742 0.20340574 0.03643315
0.62638826 0.12454928 0.64567226 0.04782684 0.88455847 0.62114705
0.82253557 0.12590787 0.99624612 0.0780055 0.38312778 0.56969024
0.21771078 0.18022973 0.06825607 0.05189065 0.19410785 0.93458232
0.84006441 0.8796388 0.00574523 0.92213916 0.60108549 0.48774697
0.79918579 0.05700109 0.42167703 0.26358089 0.37023659 0.05556867
0.1788227 0.63840475 0.79772203 0.20969062 0.55459356 0.81425831
0.06324903 0.274849 0.15092814 0.65504038 0.57138257 0.37113864
0.84318386 0.58306703 0.95677286 0.28962055 0.31085227 0.92607168
0.61132872 0.42862182 0.67385059 0.58591843 0.98309858 0.12926512
0.89650825 0.47853266 0.16842571 0.77785123 0.16004964 0.24379739
0.76415568 0.14338659 0.73812864 0.52921474 0.8678008 0.82205399
0.1219327 0.83831355 0.5219863 0.67680272 0.05486754 0.89255115
0.91609614 0.74104108 0.98763434 0.07343619 0.0879543 0.55360531
0.01048341 0.01083459 0.13080064 0.51212431 0.24552376 0.77620793
0.16560353 0.42042389]
我需要从w数组中的数字中找到最小4个值的平均值。我该怎么办?
答案 0 :(得分:2)
您可以使用heapq.nsmallest
,它应该比排序要快一点:
import heapq
import statistics
print(statistics.mean(heapq.nsmallest(4, w)))
答案 1 :(得分:1)
您可以简单地做到:
sum(sorted(w)[:4])/len(sorted(w)[:4])
答案 2 :(得分:0)
尝试对数组进行排序,并通过切片选择4个最小值,然后求平均值。
np.mean(np.sort(w)[:4])
答案 3 :(得分:0)
将numpy.partition
与kth=3
一起使用,然后取前四个值的平均值:
In [41]: np.partition(w, 3)[:4].mean()
Out[41]: 0.004304237929249388