在TCL中按索引更改列表中的项目

时间:2014-07-16 18:36:00

标签: arrays list file tcl

我试图使用这种糟糕的语言,我必须通过索引访问它来更改列表项

set FileRead [open "$flPath" r]
set Data [read $FileRead]
set DataList [split $Data "\n"] #Guess that it creates a list, not an array right?

for {set i 1} { $i < [llength $DataList]} {incr i} {
     set line [lindex $DataList $i]
     #Some changes on $line
     lreplace $DataList $i $line # Thought this should replace the DataList[$i] with my $line
}

我不明白TCL糟糕的语法!我怎么能意识到它?

2 个答案:

答案 0 :(得分:3)

你不应该只是简单地说一种语言,因为你不知道如何使用它,否则,根本就不要使用它......

无论如何,您应该阅读lreplace的{​​{3}}。你提供:

lreplace list first last ?element element ...?

要替换DataList列表中的行,您应该将行更改为:

lreplace $DataList $i $i $line

这会将i中的DataList项替换为line中的字符串。

但是,这不会更改DataList所需的列表set lreplace对变量的结果lreplace不会更改列表DataList {1}}直接)... ...

set DataList [lreplace $DataList $i $i $line]

虽然如果您一次只更改列表中的一个项目,最好使用documentation

set FileRead [open "$flPath" r]
set Data [read $FileRead]
set DataList [split $Data "\n"] #Guess that it creates a list, not an array right?

for {set i 1} { $i < [llength $DataList]} {incr i} {
     set line [lindex $DataList $i]
     # Some changes on $line
     lset DataList $i $line
}
lset不同的

lreplace不需要设置,因为除了返回替换列表之外,它还会更改列表。

答案 1 :(得分:2)

如果要更改列表中的每个项目,并且可以通过简单脚本生成新值,则lmap(列表映射)是可行的方法。该命令创建一个列表,其中包含与原始列表相同数量的项目,其中新列表中的每个项目都具有脚本的值,并且插入了原始列表中相应项目的值。假设您要计算列表中每个项目的字符数:

set list [list can be produced]
lmap item $list {
    list $item [string length $item]
}
# => {{can 3} {be 2} {produced 8}}

请注意,此命令不会更改list的值:您需要将其重新分配以更新值。

linsert(列表插入)将新项目添加到列表中,而不删除任何现有元素:

set list [list can be produced]
linsert $list 1 not
# => {can not be produced}

lreplace(列表替换)对于更改列表中元素数量的插入非常有用:

set list [list can be produced]
lreplace $list 0 1 can sometimes but not always be
# => {can sometimes but not always be produced}

set list [list the new value can be produced]
lreplace $list 1 1
# => {the value can be produced}

同样,list或[{1}}不会更改linsert的值。

如果您想更改列表中的项目,lreplace(列表集)是您的朋友:

lset

此命令 更改set list [list the new value can be produced] lset list 1 correct # => {the correct value can be produced} 的值,因为它属于设置命令系列,它采用变量名而不是变量值,并以某种方式修改值

文档:linsertlistlmaplreplacelsetsetstring