0

我的清单是:

set list {23 12 5 20 one two three four}

预期输出是按递增顺序排列的,不同之处在于字母需要放在开头:

four one three two 12 20 23 5

我尝试了以下方法:

# sorting the list in increasing order:
lsort -increasing $list
-> 12 20 23 5 four one three two
# Here i get the result with numbers first as the ascii value of numbers are higher than alphabets.

 

lsort -decreasing $list
# -> two three one four 5 23 20 12
4

2 回答 2

2

我建议拧一个比较器:

proc compareItm {a b} {
    set aIsInt [string is integer $a]
    set bIsInt [string is integer $b]

    if {$aIsInt == $bIsInt} {
        # both are either integers or both are not integers - default compare
        # but force string compare
        return [string compare $a $b]
        # if you want 5 before 12, comment the line above and uncomment the following line
        # return [expr {$a < $b ? -1 : $a > $b ? 1 : 0}]
    } else {
        return [expr {$aIsInt - $bIsInt}]
    }
}

并将其与以下-command选项一起使用lsort

lsort -command compareItm
于 2013-03-18T13:00:02.487 回答
0

最简单的方法之一是生成排序规则并按以下方式排序:

lmap pair [lsort -index 1 [lmap item $list {
    list $item [expr {[string is integer $item] ? "Num:$item" : "Let:$item"}]
}]] {lindex $pair 0}

如果您使用的是 Tcl 8.5 或 8.4(缺少lmap),请使用更冗长的版本:

set temp {}
foreach item $list {
    lappend temp [list $item [expr {
        [string is integer $item] ? "Num:$item" : "Let:$item"
    }]]
}
set result {}
foreach pair [lsort -index 1 $temp] {
    lappend result [lindex $pair 0]
}
于 2013-03-18T13:27:27.903 回答