1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

shellscriptの配列で管理している値を、pythonの標準入力に渡してリストで扱う+平均、標準偏差、最大、最小値まで求めてしまう

Last updated at Posted at 2022-02-06

shellscriptの配列で管理している値を、pythonの標準入力に渡してリストで扱う+平均、標準偏差、最大、最小値まで求めてしまう

以下の続き

shellscriptの配列で管理している値を、pythonの標準入力に渡してリストで扱う

shellscriptの配列

test.sh
arr=("100" "200" "300")
arr+=("400")
echo ${arr[@]}

pythonの標準入力に渡してリストで扱う

test.py
data = list(map(int, input().split()))

from statistics import mean, median,variance,stdev

m = mean(data)
median = median(data)
variance = variance(data)
stdev = stdev(data)
print('mean: {0:.2f}'.format(m))
print('median: {0:.2f}'.format(median))
print('variance: {0:.2f}'.format(variance))
print('stdev: {0:.2f}'.format(stdev))
print('max: {}'.format(max(data)))
print('min: {}'.format(min(data)))
print('num: {}'.format(len(data)))

実行(test.shの出力をパイプでtest.pyに渡すバージョン)

$ bash test.sh | python test.py
mean: 250.00
median: 250.00
variance: 16666.67
stdev: 129.10
max: 400
min: 100
num: 4

実行(test.shの中からtest.pyを呼び出すバージョン)

test.sh
# declare                                                                                                                                                                                            
SCORE_ARRAY=()
LOOP_TIMES=10
TMP_LOG="tmp.log"

# append array                                                                                                                                                                                       
for i in `seq ${LOOP_TIMES}`
do
    SCORE_ARRAY+=("${i}")
done

# calc static value                                                                                                                                                                                  
echo ${SCORE_ARRAY[@]} | python test.py > ${TMP_LOG}
MEAN=`cat ${TMP_LOG} | grep "mean" | cut -d' ' -f2`
STDEV=`cat ${TMP_LOG} | grep "stdev" | cut -d' ' -f2`
MAX=`cat ${TMP_LOG} | grep "max" | cut -d' ' -f2`
MIN=`cat ${TMP_LOG} | grep "min" | cut -d' ' -f2`
NUM=`cat ${TMP_LOG} | grep "num" | cut -d' ' -f2`
cat ${TMP_LOG}
echo "${MEAN}" "${STDEV}" "${MAX}" "${MIN}" "${NUM}"
$ bash test.sh
mean: 5.50
median: 5.50
variance: 9.17
stdev: 3.03
max: 10
min: 1
num: 10
5.50 3.03 10 1 10

shellscript中心の処理で、平均、標準偏差などを求めたい時に便利かも

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?