如何 "zip" 在 tcl 中列出

How to "zip" lists in tcl

我有三个列表:

set l1 {1 2 3}
set l2 {'one' 'two' 'three'}
set l3 {'uno' 'dos' 'tres'}

我想建立这个列表:

{{1 'one' 'uno'} {2 'two' 'dos'} {3 'three' 'tres'}}

python 中,我会使用类似于内置函数 zip 的东西。我应该在 tcl 做什么?我看过 documentation of 'concat',但是 还没有找到先验的相关命令。

lmap a $l1 b $l2 c $l3 {list $a $b $c}

列表映射,lmap,是一种映射命令,它从一个或多个列表中获取元素并执行脚本。它创建一个新列表,其中每个元素都是脚本执行一次的结果。

文档:list, lmap

此命令是在 Tcl 8.6 中添加的,但可以轻松添加到早期版本中。

Getting lmap for Tcl 8.5 and earlier

如果您还没有使用 Tcl 8.6(您可以在其中使用 lmap),您需要这个:

set zipped {}
foreach a $l1 b $l2 c $l3 {
    lappend zipped [list $a $b $c]
}

这实际上是 lmap 为您所做的,但它是 8.6 中的新功能。

这是一个采用任意数量的列表名称的版本:

set l1 {a b c}
set l2 {d e f}
set l3 {g h i j}

proc zip args {
    foreach l $args {
        upvar 1 $l $l
        lappend vars [incr n]
        lappend foreach_args $n [set $l]
    }
    foreach {*}$foreach_args {
        set elem [list]
        foreach v $vars {
            lappend elem [set $v]
        }
        lappend result $elem
    }
    return $result
}

zip l1 l2 l3
{a d g} {b e h} {c f i} {{} {} j}

{*} 参数扩展需要 Tcl 8.5。

8.6 版本

proc zip args {
    foreach l $args {
        upvar 1 $l $l
        lappend vars [incr n]
        lappend lmap_args $n [set $l]
    }
    lmap {*}$lmap_args {lmap v $vars {set $v}}
}