我在Tcl中有一个列表:
set list1 {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9}
Run Code Online (Sandbox Code Playgroud)
那我怎么能得到基于列表索引的元素?例如:
我想得到这个列表的第二个元素?或者这个清单的第六个?
只需使用分割和循环?
foreach n [split $list1 ","] {
puts [string trim $n] ;# Trim to remove the extra space after the comma
}
Run Code Online (Sandbox Code Playgroud)
[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
Run Code Online (Sandbox Code Playgroud)
索引从0开始,因此您必须从需要从列表中提取的索引中删除1.
小智 7
做就是了
lindex $list 2
Run Code Online (Sandbox Code Playgroud)
你会得到
0x3
Run Code Online (Sandbox Code Playgroud)