たとえば、配列出力を並べ替える方法
puts "$ word $ count($ word)"}からのサンプル入力
サンプル入力
Roger 15
Martin 18
Jemmy 16
Jon 12
Sara 12
期待される出力
Martin 18
Jemmy 16
Roger 15
Jon 12
Sara 12
Tclの配列は常にソートされておらず、実際、要素を追加すると(基になるハッシュテーブルが再構築されるときに)、要素の順序が時々変更されます。必要な出力を取得するには、配列の内容を取得lsort
し、次の-stride 2
オプションを使用することをお勧めします。
# Convert the array to a Tcl list
set contents [array get count]
# First sort by name, as a secondary key
set contents [lsort -stride 2 -index 0 $contents]
# Then sort by count, descending, as a primary key
set contents [lsort -stride 2 -index 1 -integer -decreasing $contents]
# Print the values
foreach {name score} $contents {
puts "$name $score"
}
この-stride
オプションにはTcl8.6が必要です。
古いバージョンのTclでは、物事list
をタプルにまとめる必要があります。
# Convert the array to a list of pairs
set contents {}
foreach {name score} [array get count] {
lappend contents [list $name $score]
}
# Do the sorting
set contents [lsort -index 0 $contents]
set contents [lsort -index 1 -integer -decreasing $contents]
# Print the values
foreach pair $contents {
# Unpack; *not* needed here, but useful for anything more complicated
foreach {name score} $pair break
# You could use “lassign $pair name score” but you're on 8.4
puts "$name $score"
}
Tcl 8.4はサポートされていないソフトウェアであり、セキュリティの問題もありません。また、8.5のサポート期間はあと1年か2年しか残っていないことに注意してください。人の手を握る時間には限界があります…
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加