Tcl 包含多个值的列表排序

Tcl 包含多个值的列表排序,tcl,Tcl,我有一个列表List1,需要根据某些inet值进行排序 proc compare {a b} { set L1 [ ] #Where L1 contain inet0 set L2 [ ] # Where L2 contain inet15 . . . } set sortedList [ lsort -command compare List1] 这里的列表1引用了此处关注的某些inet值 inet15 23726 inet0 23725 inet1 23727 inet

我有一个列表List1,需要根据某些inet值进行排序

proc compare {a b} {
set L1 [ ]  #Where L1 contain inet0 
set L2 [ ]  # Where L2 contain inet15
.
.
.
}

set sortedList [ lsort -command compare List1]
这里的列表1引用了此处关注的某些inet值

inet15  23726
inet0    23725
inet1   23727
inet31  23724
inet47  23720
inet5   23715
inet6   23727
进程应根据已排序的inet…返回已排序的列表1。。。。比如。我正在使用较旧版本的tcl

inet0   23725
inet1   23727
inet2   23758
inet5   23715
inet15  23726
inet31  23724

您只需使用
lsort
命令中的
-dictionary
选项即可

set input "inet15  inet0  inet1  inet31  inet47  inet5  inet6  inet7  inet8  inet9  inet10  inet11  inet32  inet13  inet14  inet2  inet16  inet17  inet18  inet20  inet19  inet21  inet22"
puts [lsort -dictionary $input]
输出:

inet0 inet1 inet2 inet5 inet6 inet7 inet8 inet9 inet10 inet11 inet13 inet14 inet15 inet16 inet17 inet18 inet19 inet20 inet21 inet22 inet31 inet32 inet47

一旦你有了这个列表,你就可以简单地从另一个列表中获取映射。

使用这个数据最简单的方法是使用
-stride
-index
选项来
lsearch
-stride
将列表拆分为按单位排序的子列表,
-index
用于选择子列表中的哪个项是排序规则键。最后,
-dictionary
选项对您要查找的键进行排序(它将字母序列和嵌入的数字视为特殊的东西)

但是,您似乎也希望保留换行符。这是可能的,但需要稍微不同的处理

# Split by newlines; in your case, we'll get a two-level list structure
set intermediate [split $List1 "\n"]
# Do the sort; don't need -stride as we already have the structure
set intermediate [lsearch -index 0 -dictionary $intermediate]
# Recombine to get newlines
set sortedList [join $intermediate "\n"]

转换为一行是留给读者的练习。

不清楚列表内容是什么。这里有一种方法,其中数组包含作为列表1中的元素的键和来自列表2的值。 然后,根据上面的示例,您可以迭代已排序的数组元素列表并获得已排序的输出

sharad@ss:~$ cat my.tcl 
array set foo {
    inet15  23726
    inet0   23725
    inet1   23727
    inet31  23724
    inet47  23720
    inet5   23715
    inet6   23727
}

foreach inet [lsort -dictionary [array names foo]] \
{
    set value $foo($inet)
    puts $inet=$value
}
sharad@ss:~$ 

Output:
sharad@ss:~$ tclsh my.tcl
inet0=23725
inet1=23727
inet5=23715
inet6=23727
inet15=23726
inet31=23724
inet47=23720
sharad@ss:~$ 
称之为使用:

lsort -command sortit $List1

我使用的是旧版本8.4。您能提供列表1和列表2的内容以及预期的输出吗?根据上面提供的信息,我在左边或右边的列中找不到模式。例如,这是一个list1 23726 23725 23727 23724 23720 23715 23727,我创建了一个应该返回排序list1的过程,因此在这个过程中,我使用某些api提取净值。所以2372615。。。在上面的第一个列表中以此类推。所以,该过程将根据inet0、inet1值对列表1进行排序。最后,我将根据inet名称对列表1进行排序,最后的名称如下:inet 0 23725 inet 1 23727 inet 2 23758 inet 5 23715 inet 15 23726 inet 31 23724
proc sortit { anum bnum } {
    set aname [zapper::extractname $anum]
    set bname [zapper::extract name $bnum]
    set sortnames [lsort -dictionary [list $aname $bname]]
    if { [ index $sortnames 0 ] != $aname } {
        return -1} else { 
           return 1 
         }
     return [list sortie [ lindex $anum 0] [ lindex $bnum 0 ]]
    }
lsort -command sortit $List1