- 6.2 基本列表结构( lindex、 llength )
- 6.3 创建列表(list、concat、lrepeat)
- 6.4 修改列表(lrange、linsert、lreplace、lset、lappend)
- 6.5 从列表中取得元素(lassign)
- 6.6 搜索列表(lsearch)
- 6.7 排序列表(lsort)
- 6.8 字符串与列表之间转化(split、join)
- 6.9 用列表创建命令
- Tcl使用列表来处理各种集合。
- 列表是元素的有序集合。
最简单的列表就是包含由任意多个空格、制表符、换行符分隔开的任意多个元素的字符串。 如aaa bbb ccc ddd
-
简单形式列表的元素不能包含空白(因为是分隔符)。
-
命令:
lindex list ?index ...?
作用:使用list的第index个元素(从0开始)% lindex {hello world} 1 world
-
命令:
llength list
作用:返回list中的元素个数% llength {hello world} 2
-
列表可以用{}嵌套 操作嵌套列表时,可以有多个索引值。
% lindex {hello {hi world} world} 1 0 hi
-
命令:
list ?value value ...?
作用:返回一个列表% list {a b c} d {e {f g}} {a b c} d {e {f g}}
-
命令:
concat ?list list ...?
作用:将多个列表合并为一个列表。% concat {a b c} d {e {f g}} a b c d e {f g}
-
命令:
lrepeat number value ?value ...?
作用:把value作为元素,重复number次得到列表% lrepeat 2 {a b c} d {e {f g}} {a b c} d {e {f g}} {a b c} d {e {f g}}
-
concat参数需要有适当的列表结构,如果某个参数不是完整的列表,那么这个命令的结果也可能不具备完整的列表形式。
-
如果不知道元素的值,使用list命令创建列表是安全的方法。
-
命令:
lrange list first last
作用:返回一个由list中first到last元素组成的列表% set x {a b {c d}} a b {c d} % lrange $x 1 2 b {c d}
-
命令:
linsert list index value ?value ...?
作用:将value参数作为列表元素插入list中的第index个元素之前。% set x {a b {c d}} % linsert $x 1 a1 a2 a3 a a1 a2 a3 b {c d}
-
命令:
lreplace list first last ?value ...?
作用:list中的first到last元素替换为value。% set x {a b c d} a b c d % lreplace $x 1 2 e a e d
- value为空即可实现删除功能。
-
命令:
lset varName ?index ...? newValue
作用:将varName列表中index索引指向的元素值替换为value。% set x {a b c d} a b c d % lset x 1 e a e c d
- lset不能创建新的列表,只能修改已存在的列表。
-
命令:
lappend varName value ?value ...?
作用:将value添加到varName中,如果varName不存在则新建。% set x {a b c d} a b c d % lappend x e f a b c d e f
- 命令:
lassign list vatName ?varName ...?
作用:把list中的元素依次赋给varName,返回剩余元素组成的列表。如果变量名多余元素数,则赋空字符串。% lassign {a b c} x y z % put ",," ,,
- 命令:
lsearch ?option ...? list pattern
作用:在list中搜索与pattern匹配的一个或多个元素。option(模式匹配方式-exact、-glob、-regexp;返回元素值(-inline)还是索引;搜索所有的匹配(-all)还是最先出现的匹配等)。默认进行通配符匹配,返回第一处匹配的索引,无匹配返回-1。
-
命令:
lsort ?option ...? list
作用:对list中的元素排序,返回排序后的列表。% lsort {f e d b c a} a b c d e f
option:
- -decreasing:从大到小。
- -interger -real:元素视为整数或实数再排序。
- -dictionary:不区分大小写,并且元素中嵌入的数字都作为非负整数处理。
- -unique:重复出现的元素只在结果出现一次。
-
命令:
split string ?splitChars?
作用:在string中出现splitChars处分开,返回列表。% set x "a,b,c,d" a,b,c,d % split $x , a b c d
-
命令:
join list ?joinString?
作用:返回以joinString作为分隔符串接元素的字符串,默认空格为分隔符。% set x {a b c d} a b c d % join $x , a,b,c,d
- Tcl中列表与命令的关系。
- 一个形式完整的Tcl命令的结构与列表是相同的。
- Tcl解析器不管遇到列表还是命令,都不进行替换操作。
button .b -text Reset -command {set x $initValue}
Tcl脚本set x $initValue
会在用户单击按钮时运行。如果initValue值为hello world,解析为set x hello world
则会导致错误。 解决:使用列表来生成这条命令: button .b -text Reset -command [list set x $initValue]
这样解析为set x {hello world}
。
% set initValue {hello world}
hello world
% list set x $initValue
set x {hello world}