2015-06-23 32 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

相關問題