如何根据TCL数组的键值对它进行排序?

问题描述:

INITIAL_ARRAY

Key -> Value
B      8
C     10
A      5
E      3
D      1

要获得基于键的排序数组,我使用

To get a sorted array based on key, I use

set sorted_keys_array [lsort [array names INITIAL_ARRAY]]

获取输出

Key -> Value
A     5
B     8
C     10
D     1
E     3

像明智的做法一样,如何根据键的获取排序的tcl数组,如下面的输出所示?

Like wise, how to get a sorted tcl array based on values of keys, like output below?

Key -> Value
 C     10
 B     8 
 A     5
 E     3
 D     1

从Tcl 8.6开始,您可以

Starting with Tcl 8.6, you could do

lsort -stride 2 -integer [array get a]

这将生成按值排序的键/值对的 flat 列表.

which would produce a flat list of key/value pairs sorted on values.

lsort获得-stride选项之前,您必须从array get返回的平面列表中构造列表列表,然后使用lsort-index选项对其进行排序:>

Before lsort gained the -stride option, you had to resort to constructing a list of lists out of the flat list array get returns and then sort it using the -index option for lsort:

set x [list]
foreach {k v} [array get a] {
    lappend x [list $k $v]
}
lsort -integer -index 1 $x