我在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]
然后删除尾随空格(如果有的话)并打印结果。
编辑:
要获取列表的第n个元素,请使用以下lindex
函数:
% puts [lindex $list1 1]
0x2
% puts [lindex $list1 5]
0x6
索引是从0开始的,因此必须从需要从列表中拉出的索引中删除1。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句