2015-06-23 31 views
2

我有一个数组名为 “test”:我怎样才能基于它的键排序TCL关联数组?

key -> value 
a  4 
f  5 
c  3 
b  0 
d  9 

而且我想作为对数组进行排序:

a 4 
b 0 
c 3 
d 9 
f 5 

我试着使用:

set sorted_array [lsort [array names test]] 

但这只能返回我:abcdf 我怎样才能得到整个数组的值(也按照键排序)?

我能够得到排序结果。现在,我试图把它作为一个名为“sorted_array”使用代码排序后的数组给出如下:

foreach idx [lsort [array names test]] { 
    append result "$idx $test($idx)" 
    set sorted_array($idx) $test($idx) 
} 

现在,当我打印阵列“sorted_array”使用:

foreach index [array names sorted_array] { 
puts "sorted_array($index): $sorted_array($index)" 
} 

但是,我得到相同数组作为“测试”,而不是一个排序的。

+1

的'parray' PROC做到这一点:在交互式会话,做'粒子阵列env'(加载PROC),然后'信息身体parray' –

+0

Tcl数组不记得按“广告订单”(字典做,但它们在旧版本的Tcl中不可用)。此外,它是一个关联数组,而关联数组没有内在排序(它是一组键 - 值对)。排序只在你想输出数组的时候有意义, –

回答

3

随着stride选项lsort,我们可以很容易地做到这一点。

-stride strideLength

如果指定该选项,该列表被视为由> strideLength元件组和所述基团是 通过它们第一元件排序或,如果-index选项是使用, 由第一个索引给定的每个组中的元素传递给 -index(然后由-index忽略)。元素始终保持在其组中的相同位置。列表长度必须strideLength,的 整数倍这又必须至少为2。

array set test { 
    a  4 
    f  5 
    c  3 
    b  0 
    d  9 
} 
puts [lsort -stride 2 [array get test]] 

输出:

a 4 b 0 c 3 d 9 f 5 

参考:lsort

更新: 如果您的版本低于8.5,那么您必须对数组的索引进行排序并获取数组值。

array set test { 
    a  4 
    f  5 
    c  3 
    b  0 
    d  9 
} 

foreach idx [lsort [array names test]] { 
    append result "$idx $test($idx) " 
} 
puts $result 

这将给出与我的第一种方法相同的输出。

更新2:

# Here, I have given 'lsort', because of appending the to 
# list in a sorted manner. Else, it is not required. 
# i.e. If you only intend to save the values into array, 
# then we don't need 'lsort' here. 
foreach idx [lsort [array names test]] { 
    append result "$idx $test($idx)" 
    set sorted_array($idx) $test($idx) 
} 
# lsort is mandatory for the array indices, so that while 
# printing the elements, it will be in sorted form. 
foreach index [lsort [array names sorted_array]] { 
    puts "sorted_array($index): $sorted_array($index)" 
} 

由于Mr.Glenn杰克曼,而不是做这样的,你也可以使用parray以显示有序数组作为输出。

parray sorted_array 
+1

我们可以用'foreach {key val} [lsort -stride ...] {puts“$ key $ value”}输出它'' –

+0

'lsort - 步幅“不适合我。有没有另一种方法来排序呢? 'bad option“-stride”:必须是-ascii,-command,-decreasing,-dictionary,-increasing,-index,-indices,-integer,-nocase,-real或-unique 执行时 “lsort -stride 2 [array get test]“' – NSU

+0

@surabhinayar:看来你的Tcl版本低于8.5,这就是它失败的原因。我已经更新了我的答案。请检查。 – Dinesh

相关问题