使用 Tcl 计算列的列的平均值

编程入门 行业动态 更新时间:2024-10-07 01:30:07
本文介绍了使用 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 计算列的列的平均值

本文发布于:2023-07-09 10:30:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085629.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:平均值   Tcl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!