【问题标题】:Creating a list in tcl with elements that in proper index positions在 tcl 中创建一个列表,其中包含正确索引位置的元素
【发布时间】:2012-11-16 07:33:06
【问题描述】:

如何使用 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} { }

谢谢

【问题讨论】:

  • 这个列表是否来自拆分字符串?如果是这样,有更好的方法从字符串中提取单词。

标签: list join split tcl concatenation


【解决方案1】:

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

# 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}]

【讨论】:

  • 你也可以全局搜索*-*
【解决方案2】:

看来你想完成两个目标:

  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]] != ""
}]

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2021-05-07
    • 2012-10-26
    • 1970-01-01
    相关资源
    最近更新 更多