Converting Columns in a List in Tcl Script

夙愿已清 提交于 2020-01-06 05:52:08

问题


I want to convert a column of a file in to list using Tcl Script. I have a file names "input.dat" with the data in two columns as follows:

7 0

9 9

0 2

2 1

3 4

And I want to convert the first column into a list and I wrote the Tcl Script as follows:

set input [open "input.dat" r]
set data [read $input]
set values [list]
foreach line [split $data \n] {

  lappend values [lindex [split $line " "] 0]
}

puts "$values"
close $input

The result shows as: 7 9 0 2 3 {} {}

Now, my question is what is these two extra "{}" and what is the error in my script because of that it's producing two extra "{}" and How can I solve this problem?

Can anybody help me?


回答1:


Those empty braces indicate empty strings. The file you used most probably had a couple empty lines at the end.

You could avoid this situation by checking a line before lappending the first column to the list of values:

foreach line [split $data \n] {
  # if the line is not equal to blank, then lappend it
  if {$line ne ""} {
    lappend values [lindex [split $line " "] 0]
  }
}

You can also remove those empty strings after getting the result list, but it would mean you'll be having two loops. Still can be useful if you cannot help it.

For example, using lsearch to get all the values that are not blank (probably simplest in this situation):

set values [lsearch -all -inline -not $values ""]

Or lmap to achieve the same (a bit more complex IMO but gives more flexibility when you have more complex situations):

set values [lmap n $values {if {$n != ""} {set n}}]



回答2:


The first {} is caused by the blank line after 3 4.

The second {} is caused by a blank line which indicates end of file.

If the last blank line is removed from the file, then there will be only one {}.

If the loop is then coded in the following way, then there will be no {}.

foreach line [split $data \n] {
    if { $line eq "" } { break }
    lappend values [lindex [split $line " "] 0]
}

@jerry has a better solution




回答3:


Unless intermittent empty strings carry some meaning important to your program's task, you may also use a transformation from a Tcl list (with empty-string elements) to a string that prunes empty-string elements (at the ends, and in-between):

concat {*}[split $data "\n"]


来源:https://stackoverflow.com/questions/55478416/converting-columns-in-a-list-in-tcl-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!