Tcl Tutorial 笔记10 · list

在tcl 中列表是一个集合:列表里可以是数字,字符,字符串,或者是其他的列表。
创建列表的几种方法:
1、手动创建列表型变量

set lst {{item 1} {item 2} {item 3}}

2、使用split命令生成列表

set lst [split "item 1.item 2.item 3" "."]

3、使用list命令

set lst [list "item 1" "item 2" "item 3"]

调用list里的值:lindex
set lst [split “item 1.item 2.item 3” “.”]
提取lst中的第二个值:
lindex $lst 1

简要说明:

split string ?splitChars?
将字符串拆分为项目列表,无论代码中出现splitChars的位置如何。 SplitChars默认为空白。请注意,如果有两个或多个splitChars,则每个单独使用一个来拆分字符串。换句话说:split“ 1234567”“ 36”将返回以下列表:{12 45 7}。

lindex index
从列表中返回第index个项目。如果列表是其他列表的列表,则可以使用多个索引-lindex listOfLists index1 index2 …

llength
返回列表中的元素数。

可以使用foreach命令来迭代列表中的项目:

 foreach {a b} $listofpairs { ... }

您甚至可以一次从多个列表中获取一个变量!例如:

    foreach a $listOfA b $listOfB {
       ...
   }
# or:
   foreach {a b} $listOfAB {
       ...
   }

此外,列表可以嵌套:

 set nestedList {
        {1 2 3}
        {A B C D}
        {xyz 33 1A}
    }
    puts "The last element from the second sublist is:"
    puts "    [lindex $nestedList 1 end]"

运行结果:

The last element from the second sublist is: D

Examples

set x "a b c d e f g h"
puts "Item at index 2 of the list {$x} is :  [lindex $x 2]\n"

set y [split 7/4/1776 "/"]
puts "we celebrate on the [lindex $y 1 ]'th day of the \
[lindex $y 0]'th month \n"

set z [list puts "arg 2 is $y"]
puts "A command resembles: $z\n"

set i 0
foreach j $x {
	puts "$j is item number $i in list x"
	incr i
}
set i 0
foreach {a b} $x {
	puts "Pair $i in list x: $a ,$b"
	incr i
}

Resulting output

Item at index 2 of the list {a b c d e f g h} is: c

We celebrate on the 4'th day of the 7'th month

A command resembles: puts {arg 2 is 7 4 1776}

a is item number 0 in list x
b is item number 1 in list x
c is item number 2 in list x
d is item number 3 in list x
e is item number 4 in list x
f is item number 5 in list x
g is item number 6 in list x
h is item number 7 in list x
Pair 0 in list x: a, b
Pair 1 in list x: c, d
Pair 2 in list x: e, f
Pair 3 in list x: g, h
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值