Reputation: 2821
I have a list eg MyList
set MyList [ list 508 1.648E-01 509 1.670E-01 510 1.701E-01 511 1.740E-01 512 1.784E-01 ]
How can I extract the Key / Value pair where: The absolute value of the values is max within the list ?? (What a sentence...)
In this case 512 1.784E-01
I would create a foreach loop and save the key value whenever the abs(Value) is greater than the previous pair. Is there a method without a loop? Im on tcl 8.5 so the "lsort -stride" trick is out of reach.
Upvotes: 2
Views: 2487
Reputation: 137717
The straight-forward way is to use dict for
to do a classic iterate-over-collection with the dictionary.
set maxVal -Inf
dict for {k v} $MyList {
if {$v > $maxVal} {
set maxKey $k
set maxVal $v
}
}
The -Inf
? A numeric value smaller than every other value. (IEEE arithmetic is great sometimes.)
Upvotes: 2
Reputation: 247022
I would create a new list containing key/value sublists
foreach {k v} $MyList {lappend newlist [list $k $v]}
Then use
lassign [lindex [lsort -real -index 1 $newlist] end] max_key max_val
Upvotes: 1