2013-11-20 90 views
0

我不是TCL的專家,但不幸的是必須處理它。我試圖做到這一點:我有一個字符串列表:例如「test2」test3「test1」。我想在「測試」之後使用數字對列表進行排序。我已經閱讀了所有的lsort命令選項,但我認爲沒有簡單的方法,因爲tcl沒有(WHY ???)將字符串視爲像python這樣的數組。我怎樣才能做到這一點 ?謝謝大家。TCL:根據字符串的一部分對字符串列表進行排序

+0

它通常沒有必要處理字符串作爲字符序列(事實上的Tcl認爲字符串是更基礎的數據類型)。當有必要時,'split $ theString {}'會給出一個字符列表。 –

回答

1

最簡單的答案是:

set yourlist {test2 test3 test1} 
puts [lsort $yourlist] 

但是,如果你有一個數字,這將失敗> 10:

set yourlist {test2 test3 test1 test11} 
puts [lsort $yourlist] 

所以,你可能需要這個比喻自己:

proc mycompare {arg1 arg2} { 
    if {[regexp {test(\d+)} $arg1 -> n1] && [regexp {test(\d+)} $arg2 -> n2]} { 
     return [expr {$n1 - $n2}] 
    } 
    return [string compare $arg1 $arg2] 
} 

set yourlist {test2 test3 test1 test11} 
puts [lsort -command mycompare $yourlist] 

事實上,Tcl可以將字符串視爲字節數組,因此與陳述

TCL沒有(爲什麼???)認爲字符串作爲數組

是你的 「陣列」 的definiton。在Tcl中我們通常使用名單值的序列,如果你想獲得的所有字符的列表中使用split $yourstring {}

+0

謝謝你的回答!我抱怨我的聲明「tcl沒有(WHY ???)將字符串視爲數組」意思是說,如果設置a =「abcde」,簡單地能夠解決(2)會更容易,但這是抱怨一個喜歡python的懶惰的人;) – user3012827

+0

好吧,要從列表中獲得第n個元素,您使用'lindex $ mylist $ n',對於使用'string index $ mystring $ n'的字符串。如果Tcl API將被重新設計,那麼所有的l *命令將被重命名爲'list ...',但是已經有一個'list'命令,這是非常重要的。 –

1

我會使用一個Schwarzian變換方法

% set l {test1 test10 test20 test3} 
test1 test10 test20 test3 
% foreach elem $l {lappend new [list $elem [regexp -inline {\d+} $elem]]}  
% set new 
{test1 1} {test10 10} {test20 20} {test3 3} 
% foreach pair [lsort -index 1 -integer $new] {lappend result [lindex $pair 0]} 
% puts $result 
test1 test3 test10 test20 

爲TCL 8.6

set result [ 
    lmap e [ 
     lsort -integer -index 1 [ 
      lmap e $l {list $e [regexp -inline {\d+} $e]} 
     ] 
    ] {lindex $e 0} 
] 
test1 test3 test10 test20 

方式題外話,與此相比,perl的

my @l = qw/ test1 test10 test20 test3 /; 
my @result = map {$_->[0]} 
      sort {$a->[1] <=> $b->[1]} 
      map {m/(\d+)/ and [$_, $1]} 
      @l; 
+0

您可以使用8.6的'lmap'來簡化... –

2

lsort命令有一個-dictionary選項,這不正是 你想要什麼:

% set lis {test1 test10 test20 test15 test3} 
test1 test10 test20 test15 test3 
% puts [lsort -dictionary $lis] 
test1 test3 test10 test15 test20 
+1

僅當_all_的前綴是'test' ... –

+0

非常感謝你,這符合我的意圖,我的教程沒有涵蓋所有的lsort選項:) – user3012827

相關問題