使用数组get后,如何删除TCL中的索引



我有一个以数组结束的proc。为了返回它,我使用"array-get"来检索列表。然而,这个列表不仅包含我的数组条目,还包含它们的索引:

所以我的数组[ a b c d ]变成了一个列表{ 0 a 1 b 2 c 3 d }

如何在不打乱列表顺序的情况下删除这些索引号?

除了使用foreach:之外,还有一些选项

# [array get] actually returns a dictionary
puts [dict values $list]
# Could do this too
set entrylist {}
dict for {- entry} $list {
    lappend entrylist $entry
}
puts $entrylist

Tcl 8.6:中有更多的可能性

puts [lmap {- entry} $list {set entry}]

(还有一个dict map,但在这里没有用。)

我喜欢dict values

我认为最简单、最基本的方法是使用foreach循环:

% set list {0 a 1 b 2 c 3 d}
% set entrylist {}
% foreach {id entry} $list {
%     lappend entrylist $entry
% }
% puts $entrylist
a b c d

如果您已经有了一个数组并使用Tcl 8.5或更高版本,请使用dict values:

set arr(0) a
set arr(1) b
set arr(2) c
set arr(3) d
puts [dict values [array get arr]]

但最好使用简单的list:

set mylist {a b c d}
lset list 1 boo
puts [lindex $mylist 1]
lappend mylist eff

阵列是关联的。总是

最新更新