我有兩個陣列,percentiles并percentile_bounds和另一個int值total_score。鑒于總分,我想回傳該值所在的百分位數。IE。我想回傳一個值從percentiles對應于放置total_score內percentile_bounds。在 python 中,我會這樣做:
import numpy as np
percentiles = np.array([ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95])
percentile_bounds = np.array([ 84, 104, 109, 115, 120, 123, 125, 127, 129, 132, 135, 136, 137, 139, 141, 145, 148, 151, 155, 159])
# example 1
total_score = 130
print(percentiles[np.where(percentile_bounds==(percentile_bounds[percentile_bounds<total_score][-1]))])
# 40
# example 2
total_score = 153
print(percentiles[np.where(percentile_bounds==(percentile_bounds[percentile_bounds<total_score][-1]))])
# 85
# example 3
total_score = 100
print(percentiles[np.where(percentile_bounds==(percentile_bounds[percentile_bounds<total_score][-1]))])
# 0
我在 PHP 中找到了一種方法(函式來源:1 , 2),但它非常笨拙且冗長:
<?php
// Example 4
$total_score = 120;
$percentile_bounds = [84, 104, 109, 115, 120, 123, 125, 127, 129, 132, 135, 136, 137,139, 141, 145, 148, 151, 155, 159];
$percentiles = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95];
// get the last element from percentile_bounds which is less than total_score
$value = end(array_filter($percentile_bounds, function ($x) use ($total_score) { return $x < $total_score; }));
// find its index
$key = array_search($value, $percentile_bounds);
// find the corresponding value in percentiles
echo "percentile: $percentiles[$key]";
// 15
是否有更好的方法percentiles根據元素 ( total_score) 在另一個陣列 ( percentile_bounds) 中的位置從一個陣列 ( )中選擇元素?
謝謝
注意:它不是this的副本。
Clarification: For total_score<=84 the result should be 0 (based on how percentiles work) but it also should not happen. In the code above I do not deal with this condition so it's ok not to but if the solution does, the better :). Thanks @jspit for pointing it out!
uj5u.com熱心網友回復:
foreach 與 array_filter
$total_score = 153;
$percentile_bounds = [84, 104, 109, 115, 120, 123, 125, 127, 129, 132, 135, 136, 137, 139, 141, 145, 148, 151, 155, 159];
$percentiles = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95];
foreach ($percentile_bounds as $key => $bound) {
if ($bound > $total_score) {
echo 'percentile: ' . $percentiles[max(0, $key - 1)];
break;
}
}
uj5u.com熱心網友回復:
echo $percentiles[max(array_keys(array_filter($percentile_bounds,function ($x) use ($total_score){return $x<$total_score; })))]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/340809.html
上一篇:C帶有列印和陣列的反向數字
下一篇:PHP檔案處理讀寫
