您的位置:首页 > 其它

tcltk实例详解——列表操作(二)

2008-04-28 10:50 686 查看
列表操作在脚本中使用的频率非常高,基本上每个脚本都会涉及到其中的一些操作,在这里对列表的命令进行实例解析,以加深对列表命令的理解,本文涉及的命令为llength、lindex、lrange、lsearch和lassign。

llength list
返回一个列表的元素个数,非常简单而又常用的命令。
% llength {This is a tcltk example}
5

lindex list ?index...?
根据索引值,找出列表中索引为index的元素,如果没有index就返回整个列表,如果有多个index就返回列表的子列表的元素,具体示例如下:
返回整个列表:
% lindex {This is a tcltk example}
This is a tcltk example
返回列表中索引为3的元素:
% lindex {This is a tcltk example} 3
tcltk
返回列表中索引为2的元素
% lindex {{This is} a {tcltk example}} 2
tcltk example
返回列表中索引为2的子列表中索引为1的元素
% lindex {{This is} a {tcltk example}} 2 1
example

lrange list first last
返回列表一个区间的元素,这个区间由first和last指定。
% lrange {This is a tcltk example} 1 3
is a tcltk

lsearch ?options? list pattern
在列表中寻找元素,这里的标志位比较多,下面一一介绍,多个标志位可以互相混用。
以下是匹配风格标志位:
寻找的列表元素严格匹配pattern,也就是说pattern就是列表中的一个元素才能找到,返回元素的索引:
% lsearch -exact {This is a tcltk example} is
1
以glob风格匹配pattern,没有匹配风格标志位的话默认就是glob,搜索以is结尾的字符:
% lsearch -glob {This is a tcltk example} *is
0
以正则表达式风格匹配,搜索以is结尾的字符:
% lsearch -regexp {This is a tcltk example} .*is
0
以下是一些修饰标志位:
返回所有符合匹配风格的元素索引:
% lsearch -all {This is a tcltk example} *is
0 1
返回符合匹配风格的元素值而不是索引:
% lsearch -inline -all {This is a tcltk example} *is
This is
返回不符合匹配风格的元素索引:
% lsearch -not -all {This is a tcltk example} *is
2 3 4
从指定的索引开始搜索,下面的例子只返回了索引1,没有返回索引0:
% lsearch -start 1 -all {This is a tcltk example} *is
1
内容描述标志位:
所匹配的内容为ASCII码,使用-ascii标志位,默认就是。
可以和-sorted一起使用-dictionary来标志以字典顺序匹配。
使用-integer说明列表元素被当作整数匹配。
-real说明列表元素被当作浮点数匹配。
-nocase忽略大小写:
% lsearch -nocase {This is a tcltk example} this
0
还有两个排序标志位,需要和sorted一起使用,-decreasing和-increasing分别代表降序和升序。
两个嵌入式标志位:
-index,匹配子列表中的索引,下面的例子匹配子列表中的第二个元素,有这个标志位要求list中每个元素都必须有子列表,并且有需要检查的index:
% lsearch -index 1 -all {{This is} {b a} {tcltk example}} *a*
1 2
-subindices,需要和-index一起使用,返回匹配的全路径:
% lsearch -index 1 -all -subindices {{This is} {b a} {tcltk example}} *a*
{1 1} {2 1}

lassign list varName ?varName ...?
将列表元素赋值给变量,直接采用help里面的例子,非常明确了:
lassign {a b c} x y z ;# 返回空
puts $x ;# Prints "a"
puts $y ;# Prints "b"
puts $z ;# Prints "c"

lassign {d e} x y z ;# 返回空
puts $x ;# Prints "d"
puts $y ;# Prints "e"
puts $z ;# Prints ""

lassign {f g h i} x y ;# 返回"h i"
puts $x ;# Prints "f"
puts $y ;# Prints "g"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: