tcltk實例詳解——列表操作(二)

    列表操作在腳本中使用的頻率非常高,基本上每個腳本都會涉及到其中的一些操作,在這裏對列表的命令進行實例解析,以加深對列表命令的理解,本文涉及的命令爲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"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章