在 TCL 中查找字符串中所有数字之和的最优雅方法是什么?
What is the most elegant way to find the sum of all numbers in a string in TCL?
在以下格式的 TCL 字符串中查找所有数字之和的最优雅方法是什么?
例如
set s1 "{A 30.8950} {B 29.5680} {C 20.5160}"
如何求和,30.8950 + 29.5680 + 20.5160?
'elegant' 方法取决于您如何提取所需的输入。
下面的代码简单地遍历列表并提取数值。
set s1 "{A 30.8950} {B 29.5680} {C 20.5160}"
set sum 0
foreach elem $s1 {
# Extracting 2nd element to get the numerical value
set num [lindex $elem 1]
set sum [expr {$sum+$num}]
}
puts $sum
输出:
80.979
如果它真的只是漂浮在一个字符串中,你可以使用类似的东西:
set sum [tcl::mathop::+ {*}[regexp -all -inline {-?\d+(?:\.\d+)(?:e[-+]?\d+)} $theString]]
如果它比这更结构化,例如 Tcl 元组列表,其中每个元组的第二项是要添加的值,您可以使用:
set sum [tcl::mathop::+ {*}[lmap tuple $theList {lindex $tuple 1}]]
# Requires Tcl 8.6
在以下格式的 TCL 字符串中查找所有数字之和的最优雅方法是什么? 例如
set s1 "{A 30.8950} {B 29.5680} {C 20.5160}"
如何求和,30.8950 + 29.5680 + 20.5160?
'elegant' 方法取决于您如何提取所需的输入。
下面的代码简单地遍历列表并提取数值。
set s1 "{A 30.8950} {B 29.5680} {C 20.5160}"
set sum 0
foreach elem $s1 {
# Extracting 2nd element to get the numerical value
set num [lindex $elem 1]
set sum [expr {$sum+$num}]
}
puts $sum
输出:
80.979
如果它真的只是漂浮在一个字符串中,你可以使用类似的东西:
set sum [tcl::mathop::+ {*}[regexp -all -inline {-?\d+(?:\.\d+)(?:e[-+]?\d+)} $theString]]
如果它比这更结构化,例如 Tcl 元组列表,其中每个元组的第二项是要添加的值,您可以使用:
set sum [tcl::mathop::+ {*}[lmap tuple $theList {lindex $tuple 1}]]
# Requires Tcl 8.6