I have a list in Tcl as:
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]
去除字符串末尾的空格(如果有的话),并输出结果。
编辑:
要获取列表的第n个元素,请使用lindex
函数:
% puts [lindex $list1 1]
0x2
% puts [lindex $list1 5]
0x6
只需执行
lindex $list 2
您将获得
0x3
> set list1 {0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9}
> 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9
> lindex $list1 3
> 0x4