如果嵌套列表符合条件,我正在寻找一种不错的简短方法来从列表列表中获取第 n 个项目。 所以如果我有这个列表:
set x [list [list a 1] [list b 2] [list a 3] [list b 4]]
查找列表中第一项为“a”的所有第二项 我想得到 {1 3}。 (列表是一个键值对,所以简而言之我想要指定键的所有值)。
这样做的工作:
lsearch -all -index 1 -inline -subindices [lsearch -all -index 0 -inline $x a] *
但我正在寻找一种更简洁、更短的方法来做到这一点。
谢谢!
最佳答案
在 8.5 中,我建议坚持使用现有的版本。在 Tcl 8.6 中,您可以使用 lmap
:
lmap i $x {lassign $i k v; if {$k ne "a"} continue; set v}
lmap i $x {if {[lindex $i 0] ne "a"} continue {lindex $i 1}}
我不确定你喜欢哪一个。 (第二个有点长,也有点棘手,但生成更好的字节码。带有 lsearch
的版本在任何版本中都没有字节码。)
关于TCL 从列表列表中匹配的每个列表中获取第 n 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17563193/