使用 Tcl 计算列的列的平均值 [英] Calculate average of columns of column with Tcl
本文介绍了使用 Tcl 计算列的列的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用 tcl 计算此列的平均值请帮帮我
I want to calculate the average for this column with tcl please help me
frame Elec
1 50
2 40
3 30
4 20
推荐答案
如果这是一个独立的脚本,(警告:提前自我提升),我写了一个 名为 tawk
的程序与 awk
类似,只是使用 TCL 进行脚本编写,它为您完成大部分工作:
If this is for a standalone script, (Warning: Self promotion ahead), I wrote a program called tawk
that's like awk
except using TCL for scripting, which does most of the work for you:
$ tawk 'line {$NR > 1} { incr sum $F(2) }
END { puts [expr {double($sum) / ($NR - 1)}] }' input.txt
35
# Equivalent awk:
$ awk 'NR > 1 { sum += $2 } END { print (sum / (NR - 1)) }' input.txt
35
如果它是更大程序的一部分,您必须自己打开文件并阅读和拆分行.也许像
If it's part of a larger program, you have to open the file and read and split lines yourself. Maybe something like
# Column number is 1-based
proc avg_column {filename column} {
set f [open $filename r]
gets $f ;# Read and discard header line
set sum 0
set nlines 0
while {[gets $f line] >= 0} {
set columns [regexp -all -inline {\S+} $line]
incr sum [lindex $columns $column-1]
incr nlines
}
close $f
return [expr {double($sum) / $nlines}]
}
puts [avg_column input.txt 2]
这篇关于使用 Tcl 计算列的列的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文