我在 Tcl 中有一个列表:
set list1 {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9}
那么如何根据列表的索引获取元素呢?例如:
我想得到这个列表的第二个元素?还是这个列表的第六个?
最佳答案
只使用拆分和循环?
foreach n [split $list1 ","] {
puts [string trim $n] ;# Trim to remove the extra space after the comma
}
[split $list1 ","]
返回一个包含 0x1 { 0x2} { 0x3} { 0x4} { 0x5} { 0x6} { 0x7} { 0x8} { 0x9}
的列表foreach
循环遍历列表的每个元素并将当前元素分配给 $n
。[string trim $n]
然后删除尾随空格(如果有)并 puts 打印结果。编辑:
要获取列表的第 n 个元素,请使用
lindex
函数:% puts [lindex $list1 1]
0x2
% puts [lindex $list1 5]
0x6
该索引是基于 0 的,因此您必须从需要从列表中提取的索引中删除 1。
关于list - 如何从 Tcl 中的列表中获取值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19136611/