查找生成 200 个随机数的数组中最小 4 个值的平均值

我在 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


我需要从 w 数组中的数字中找到最小的 4 个值的平均值。我该怎么做?


缥缈止盈
浏览 183回答 3
3回答

开满天机

您可以使用heapq.nsmallestwhich 应该比排序稍快:import heapqimport statisticsprint(statistics.mean(heapq.nsmallest(4, w)))

交互式爱情

你可以简单地做:sum(sorted(w)[:4])/len(sorted(w)[:4])

温温酱

尝试对数组进行排序并通过切片选择 4 个最小值,然后找到平均值。np.mean(np.sort(w)[:4])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python