私は連想配列またはハッシュを持っていますが、ハッシュのキーを操作できる方法はありますか?
例:ハッシュのキーセットにキーのセットがあるとしましょう。これらのキーに対していくつかの操作(いくつかの文字列操作)を実行したいとします。
これを行う方法について何か提案はありますか?
すべてのキーのリストを取得するために使用array names myarray
すると、必要に応じて任意の文字列操作を行うことができます
あなたが配列について話しているのか、辞書の値について話しているのか、あなたの質問からはよくわかりません。どちらも連想マップですが、配列は変数のコレクションであり、辞書は1次値です。
コマンドを使用して配列のキーを取得し、次のarray names
コマンドを使用して辞書のキーを取得できdict keys
ます。
# Note, access with*out* $varname
set keys [array names theArray]
# Note, access *with* $varname
set keys [dict keys $theDict]
どちらの場合も、keys
変数はその後、任意の方法で操作できる文字列の通常のTclリストを保持します。ただし、これらの変更は元の場所に反映されません(これは、Tclの値のセマンティクスがどのように機能するかではなく、実際のコードでは非常に混乱するためです)。配列または辞書のエントリのキーを変更するには、古いキーを削除して新しいキーを挿入する必要があります。これにより、(おそらく)反復順序が変更されます。
set newKey [someProcessing $oldKey]
if {$newKey ne $oldKey} { # An important check...
set theArray($newKey) $theArray($oldKey)
unset theArray($oldKey)
}
set newKey [someProcessing $oldKey]
if {$newKey ne $oldKey} {
dict set theDict $newKey [dict get $theDict $oldKey]
dict unset theDict $oldKey
}
Tcl 8.6.0以降dict map
では、辞書を使用してこの種の変更を行うこともできます。
set theDict [dict map {key value} $theDict {
if {[wantToChange $key]} {
set key [someProcessing $key]
}
# Tricky point: the last command in the sub-script needs to produce the
# value of the key-value mapping. We're not changing it so we use an empty
# mapping. This is one of the many ways to do that:
set value
}]
大きな辞書でいくつかのキーを変更する場合は、前述のようにdict set
/を使用する方が効率的です。多くの変更が行われる場合に最適化されます。dict unset
dict map