arrays - 如何用 Tcl 脚本计算每列的平均值
问题描述
我需要使用文本文件中的 tcl 脚本计算每列的平均值,请帮助我
Frame Time Elec VdW Nonbond Total
0 0 -216.63 -16.0174 -232.647 -232.647
1 1 -196.786 -28.6093 -225.395 -225.395
2 2 -277.05 -23.924 -300.974 -300.974
3 3 -203.854 -30.2473 -234.101 -234.101
解决方案
一旦开始处理许多列,将整个文件拉入内存就变得更容易了。(即使对于令人惊讶的大文件,这也很有效。)
# Read the lines in
set f [open $filename]
set lines [split [string trim [read $f]] "\n"]
close $f
# Do an initial clean up of the data; \S+ matches non-whitespace
set headers [regexp -all -inline {\S+} [lindex $lines 0]]
set data [lmap line [lrange $lines 1 end] {regexp -all -inline {\S+} $line}]
# Properly we'd also validate the data to handle non-numeric junk, but this is just an example...
现在我们可以定义一个过程来按名称获取列的平均值:
proc columnAverage {name} {
global headers data
# Look up which column it is
set idx [lsearch -exact $headers $name]
if {$idx < 0} {
error "no such column \"$name\""
}
# Get the data from just that column
set column [lmap row $data {lindex $row $idx}]
# Calculate the mean of the column: sum / count
return [expr {[tcl::mathop::+ {*}$column] / double([llength $column])}]
}
你会这样称呼它:
puts "average of Elec is [columnAverage Elec]"
推荐阅读
- blueprism - 可以在单个 VM 中安装多个 Blue Prism 运行时资源吗?
- python - 记录python更改日志级别文本
- php - 如何使用 preg_match_all 从字符串中获取单词
- javascript - 不明白我使用 parseFloat 时发生了什么
- vue.js - 在 Vue 模板中渲染表格
- c# - POST csv 文件 httpclient C# 和 application/x-www-form-urlencoded
- html - 使用 Ubuntu 时如何从 angular4 中删除哈希 (#)
- asp.net - Angular 5.2 使用 Asp.net core 2.1 更新到 Angular 6 Visual Studio mac 7.5.2
- r - Change the colour of a subset of labels in barplot R
- cloudcaptain - boxfuse 的默认配置参数