2

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.

Lumpi
  • 2,697
  • 5
  • 38
  • 47
  • 1
    When I have key/value pairs, I usually store them in pairs, in a list, like `[list {key1 value1} {key2 value2} ...]`, and that way, I can use `lsort -index 1 $MyList`. – Jerry Jan 28 '14 at 16:35

2 Answers2

2

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.)

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • I've no idea if this will be faster than Glenn's answer. For short collections of data, maybe not. Someone ought to test. But for large dictionaries, this should win as it is a simple O(N) scan instead of a O(N) scan followed by a O(NlogN) sort… – Donal Fellows Jan 28 '14 at 22:41
1

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352