如何在 TCL 中创建和迭代散列哈希? [英] How do I create and iterate through a hash of hashes in TCL?

查看:35
本文介绍了如何在 TCL 中创建和迭代散列哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 TCL 中创建和迭代散列的散列?

How do I create and iterate through a hash of hashes in TCL?

如果我有这样的数据:

foo = {
    a => {
        aa => { aa1 aa2 aa3 }
        ab => { ab1 ab2 ab3 }
        ac => { ac1 ac2 ac3 }
    }
    b => {
        ba => { ba1 ba2 ba3 }
        bb => { bb1 bb2 bb3 }
        bc => { bc1 bc2 bc3 }
    }
    c => {
        ca => { ca1 ca2 ca3 }
        cb => { cb1 cb2 cb3 }
        cc => { cc1 cc2 cc3 }
    }
}

如何通过一次插入一个叶节点数据项来创建这样的散列.类似的东西:

How do I create such a hash by inserting one leaf-node data item at a time. Something like:

追加 foo(a)(ab) "ab1"

lappend foo(a)(ab) "ab1"

那么如何遍历所有数据元素?喜欢:

Then how do I iterate over all data elements? like:

foreach key in foo {
    foreach sub_key in foo($key) {
        foreach elem in foo($key)($sub_key) {
            puts "foo\($key\)\($sub_key\) is $elem"
        }
    }
}

不幸的是,我无权使用较新的dict"结构.

Edit : Unfortunately, I do not have access to the newer 'dict' construct.

推荐答案

如果您没有使用 Tcl 8.5,那么您可以使用数组.请注意,数组是一维的,但键是可用于伪造多维的任意字符串:

If you're not using Tcl 8.5, then you can use arrays. Note that arrays are one-dimensional, but the key is an arbitrary string that can be used to fake multi-dimensionality:

array set foo {}
foreach first {a b c} {
    foreach second {a b c} {
        foreach third {1 2 3} {
            lappend foo($first,$first$second) "$first$second$third"
        }
    }
}
parray data

并输出——注意:数组键与字典键不同,是无序的:

and output it -- note: array keys, unlike dictionary keys, are unordered:

foreach key [array names foo] {
    foreach elem $foo($key) {
        puts "$key\t$elem"
    }
}

如果您获得键(例如b"和bc"),您可以这样获得值:

If you are given the keys (example 'b' and 'bc') you can get the value thusly:

set key1 b
set key2 bc
foreach elem $foo($key1,$key2) {puts $elem}

这篇关于如何在 TCL 中创建和迭代散列哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆