Tcl/Tk: 如何追加或插入嵌套列表?

Tcl/Tk: How do I append or insert into a nested list?

我有两个列表 - 每个列表都包含嵌套列表 - 我想将它们组合成第三个列表。

当我尝试按如下方式使用 lappend 时,我的新列表仅包含第二个列表中的元素,以及第一个列表中的 none 个元素。

% set list1 {{a b c} {d e f} {g h i}}
{a b c} {d e f} {g h i}
% set list2 {j k l} {m n o} {p q r}}
extra characters after close-brace
% set list2 {{j k l} {m n o} {p q r}}
{j k l} {m n o} {p q r}
% set list3 [lappend [lindex $list1 0] [lindex $list2 0]]
{j k l}

我希望这会 return

{a b c j k l}

类似地,当我尝试使用 linsert 时,出现 "bad index" 错误:

% set list3 [linsert [lindex $list1 0] [lindex $list2 0]]
bad index "j k l": must be integer?[+-]integer? or end?[+-]integer?

有什么想法吗?

理想情况下,我想使用我的两个列表,并遍历每个嵌套列表,以便我的输出产生

{a b c j k l} {d e f m n o} {g h i p q r}

lappend 命令的第一个参数是一个列表变量名。 您将名称传递给它 {a b c}。

您可以使用concat命令将两个列表连接在一起创建 一个列表。

set list3 [concat [lindex $list1 0] [lindex $list2 0]]

或者使用 list 和扩展创建一个新列表:

set list3 [list {*}[lindex $list1 0] {*}[lindex $list2 0]]

要遍历列表,您可以使用:

foreach {item1} $list1 {item2} $list2 {
   ...
}

Tcl 8.6 有一个操作可以让你 lappend 一个元素 直接进入嵌套列表:

lset theListVariable $index end+1 $theItemToAdd

例如(互动环节):

% set lst {a b c d}
a b c d
% lset lst 1 end+1 e
a {b e} c d
% lset lst 1 end+1 f
a {b e f} c d

这意味着我们会像这样进行您的整体操作:

set list3 $list1
set index 0
foreach sublist $list2 {
    foreach item $sublist {
        lset list3 $index end+1 $item
    }
    incr index
}

或者,更有可能通过串联:

set list3 [lmap a $list1 b $list2 {
   list {*}$a {*}$b
}]

使用 list 扩展所有参数进行列表连接。您可以改用 concat,但有时不会执行 list concat(出于复杂的向后兼容性原因)。

linsert你会写:

set joined [linsert [lindex $list1 0] end {*}[lindex $list2 0]]  ;# => a b c j k l

我们指定要在 list1 第一个元素的 end 处插入 list2

第一个元素的元素