1

如何使用 tcl 将以下字符串/列表转换为第一个元素为 1-81 第二个元素为 81-162 第三个元素 us 162-243 的列表

{} {} {1 -81} { } {81 -162} { } {162 -243} { } {243 -324} { } {324 -405} { } {405 -486} { } {486 -567 } { } {567 -648} { } {648 -729} { } {729 -810} { } {810 -891} { } {891 -972} { } {972 -1053} { } {1053 -1134} { }

谢谢

4

2 回答 2

2

如果您只想过滤掉空列表元素,那么显而易见的做法是:

# Assuming the original list is in $list

set result {}
foreach x $list {
    if {[string trim $x] != ""} {
        lappend result $x
    }
}

# The result list should contain the cleaned up list.

请注意,[string trim]如果您确定所有空元素确实是空的并且不包含空格(意思是{}而不是可能{ }),则不需要这样做。但是您的示例同时包含空元素和空格,因此您需要进行字符串修剪。

或者,您可以使用正则表达式进行测试:

foreach x $list {
    # Test if $x contains non-whitespace characters:
    if {[regexp {\S} $x]} {
        lappend result $x
    }
}

但是,您可以使用 lsearch 在一行中执行上述操作:

# Find all elements that contain non whitespace characters:

set result [lsearch -inline -all -regexp $list {\S}]
于 2012-11-16T09:36:53.543 回答
0

看来您想实现两个目标:

  1. 从原始列表中删除所有空项目
  2. 对于每个非空项目,删除空间

我想提供一种不同的方法:使用具有过滤器命令的 struct::list:

package require struct::list

set oldList {{} {} {1 -81} { } {81 -162} { } {162 -243} { } {243 -324} {}}
set newList [struct::list filterfor item $oldList {
    [set item [string map {{ } {}} $item]] != ""
}]

在这个解决方案中,我使用了struct::list filterfor类似于 foreach 命令的命令。filterfor 的主体是一个布尔表达式。在正文中,我使用字符串映射从每个项目中删除所有空格,并且仅当结果不为空时才返回 true。此解决方案可能不是最有效的,而是解决问题的不同方法。

于 2012-11-16T15:51:24.380 回答