2012-11-16 22 views
1

如何將下面的字符串/列表轉換爲第一個元素爲1-81的列表第二個元素爲81-162第三個元素us 162-243使用tcl在tcl中用正確索引位置的元素創建列表

{} {} {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} {}

感謝

+0

這個列表是來自分割一個字符串嗎?如果是這樣,有更好的方法從字符串中提取單詞。 –

回答

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]。但是你的例子包含空的元素和空白,所以你需要做字符串修剪。

或者您可以使用正則表達式來測試:

# Find all elements that contain non whitespace characters: 

set result [lsearch -inline -all -regexp $list {\S}] 
+0

你也可以全局搜索'* - *' –

0

看來要實現兩個目標:

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

可以使用lsearch但是做到上面的一行:

  1. 刪除原始列表中的所有空項目
  2. 對於每一個非空項,刪除空間

我想提供一種不同的方法:使用結構::名單,其中有一個過濾器命令:

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。這種解決方案可能不是最有效的,但解決問題的方法不同。