如何根据TCL数组的键值对它进行排序? [英] How can I sort a TCL array based on the values of its keys?

查看:354
本文介绍了如何根据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

这篇关于如何根据TCL数组的键值对它进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆