如何在 TCL 中创建并迭代哈希值的哈希值?
如何在 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 }
}
}
如何通过一次插入一个叶节点数据项来创建这样的哈希。像这样:
lappend foo(a)(ab) "ab1"
那么如何迭代所有数据元素?喜欢:
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”结构。
How do I create and iterate through a hash of hashes in TCL?
If I have data like:
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:
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"
}
}
}
Edit :
Unfortunately, I do not have access to the newer 'dict' construct.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您使用的是 Tcl 8.5+,则可以使用字典:
定义字典很简单:
或以编程方式定义它:
并输出它:
编辑:移动数组解决方案(非字典)一个单独的答案。
Assuming you're using Tcl 8.5+, dictionaries are the way to go:
Define the dictionary is simply done:
Or define it programmatically:
And output it:
edit: moved the array solution (non-dict) to a separate answer.
如果您不使用 Tcl 8.5,则可以使用数组。请注意,数组是一维的,但键是任意字符串,可用于伪造多维性:
并输出它 - 注意:数组键与字典键不同,是无序的:
如果给定键(例如'b' 和 'bc') 你可以这样得到值:
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:
and output it -- note: array keys, unlike dictionary keys, are unordered:
If you are given the keys (example 'b' and 'bc') you can get the value thusly:
如果您只想在没有 dict 命令的情况下迭代 dict(这只是一个键值对列表),那么您可以简单地使用 foreach 的强大功能:
另一方面,如果没有 dict,一次插入一个元素是痛苦的命令:
幸运的是,您可以使用 dict 命令的纯 tcl 实现: 向前兼容的 dict
If you just want to iterate through a dict (which is simply a key-value pair list) without the dict command then you can simply use the awesomeness of foreach:
on the other hand, inserting elements one at a time is painful without the dict command:
fortunately you can use a pure-tcl implementation of the dict command: forward-compatible dict
如果您没有 Tcl 8.5 字典,请使用键控列表命令来完成工作。您可以通过 google 搜索以下术语之一:keylget、keylset。
If you don't have the luxury of the Tcl 8.5 dictionary, use the keyed list commands to get the job done. You can google for one of these terms: keylget, keylset.