问题
I need to handle kind of complex data with tcl. I need 3 dimension list to store the data, but I find tcl is bad for this work.
Based on my current study, tcl does not support simple index of list like: listname(index).
So for multiple dimension list, if I want to assign a new value for certain element, it will be very troubling.
Are there some skills to handling data effectively?
回答1:
The most efficient representation for a multi-dimensional array is a nested list (unless you're going for a sparse array). To help with this, you have lrepeat
for creation, multi-index lindex
for reading, and lset
for writing.
# Create a 5x5x5 structure, filled with float zeroes
set example [lrepeat 5 [lrepeat 5 [lrepeat 5 0.0]]]
# Index into the structure
set value [lindex $example 1 2 3]
# Write a value back into the structure
lset example 1 2 3 [expr {$value + 8.75}]
The implementation uses an efficient copy-on-write scheme for lists (including nested lists) so that you get space-saving where possible and minimal duplication where necessary in order to maintain the illusion that it's all a pure value with aggressive copying. Except much faster…
Of course, if you're doing this a lot, you might be better off having a look at VecTcl.
回答2:
If you want listname(index), you can also try arrays instead. Multi dimensional arrays are easy, as you can simply set your index as appropriate:
set example(1,2,3) $value
set value $example(1,2,3)
I don't know which would be more efficient, arrays, lists as in Donal's example or a dictionary:
dict set example 1 2 3 $value
set value [dict get $example 1 2 3]
来源:https://stackoverflow.com/questions/26378982/it-is-difficult-to-handle-multiple-dimension-list-with-tcl