1

我有一个关联数组或哈希,有没有办法可以对哈希的键进行操作。

例如:假设我在 Hash 的 Keyset 中有一组键,我想对这些键进行一些操作(一些字符串操作)。

关于如何做到这一点的任何建议?

4

2 回答 2

2

用于array names myarray检索所有键的列表,然后您可以根据需要对它们进行任何字符串操作

于 2012-12-15T23:21:06.097 回答
0

从您的问题中,我不太确定您是在谈论数组还是字典值;两者都是关联映射,但数组是变量的集合,字典是一阶值。

您可以使用命令获取数组的键,使用以下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针对进行大量更改的情况进行了优化。

于 2012-12-16T07:44:08.913 回答