在列表的特定索引列表中获取项目 [英] Get items in specific index list of lists
问题描述
我有一个键值列表,例如:
I have a key-value list such as:
set x {{a 1} {b 2} {c 3}}
我需要提取所有子列表中 index=1 中的所有项目以获取:
I need to extract all the items in index=1 in all sub-lists to get:
{1 2 3}
推荐答案
一种解决方案是征服 dict值
命令:
One solution is to conscript the dict values
command:
dict values [concat {*}{{a 1} {b 2} {c 3}}]
工作方式: dict值
收集一个列表,该列表由另一个列表中的所有其他项(从第二个开始)组成.它打算用于字典,但是由于字典基本上只是偶数大小的列表,因此它适用于任何偶数大小的列表,但有一个警告:如果任何键出现多次,则 dict values
将仅包含与该键关联的最后一个值.
How this works: the dict values
collects a list consisting of every other item (starting from the second) in another list. This is intended to be used on dictionaries, but since dictionaries are basically just even-sized lists, it works on any even-sized list, with one caveat: if any key appears more than once, the result of dict values
will only contain the last value associated with that key.
由两个项目的子列表组成的列表可以通过将子列表作为参数分别传递给 concat
轻松地转换为偶数大小的列表.
A list consisting of two-item sublists can easily be transformed into an even-sized list by passing the sublists individually as arguments to concat
.
另一种方法是使用其他答案中提到的方法之一遍历列表,或者也许像这样:
Another way is to traverse the list using one of the methods mentioned in the other answers, or maybe like this:
set res {}
for {set i 0} {$i < [llength $x]} {incr i} {
lappend res [lindex $x $i 1]
}
set res
这类似于
set res {}
foreach item $x {
lappend res [lindex $item 1]
}
set res
(或相应的 lmap项$ x {lindex $ item 1}
)
,但确实提供了以下选项:1)从索引≠开始;0、2)在列表末尾之前结束,以及3)通过两个(或更多)项目步骤遍历列表.
but does provide the option to 1) start at an index ≠ 0, 2) end before the end of the list, and 3) traverse the list by two (or more) item steps.
文档:concat , dict , foreach , lappend ,长度,设置
Documentation: concat, dict, for, foreach, incr, lappend, lindex, llength, lmap, set
这篇关于在列表的特定索引列表中获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!