2015-12-12 60 views

回答

2

如果真的只是漂浮在一個字符串,你使用類似:

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 
2

'優雅'的方法取決於你如何提取所需的輸入。

下面的代碼簡單地遍歷列表並提取數值。

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 
相關問題