sorting - 按值对 Tcl 字典排序

标签 sorting dictionary tcl

我想知道 Tcl 中是否有一种优雅的方式按值对 dict 进行排序。

假设我有以下字典:

set d1 [dict create k1 10 k2 89 k3 1 k4 15 k5 20]
# Results in dict of form
# k1 => 10
# k2 => 89
# k3 => 1
# k4 => 15
# k5 => 20

现在我想对这本字典进行排序,以便我:

# k3 => 1
# k1 => 10
# k4 => 15
# k5 => 20
# k2 => 89

我希望有类似于Python的sorted()的东西。

最佳答案

如果您有 Tcl 8.6(这利用了字典可以廉价地与列表相互转换的事实):

set sorted [lsort -integer -stride 2 -index 1 $d1]

如果您仍在使用 8.5(可能;8.6 仍处于测试阶段),那么您需要执行以下几个步骤:

proc sortDictByValue {dict args} {
    set lst {}
    dict for {k v} $dict {lappend lst [list $k $v]}
    return [concat {*}[lsort -index 1 {*}$args $lst]]
}
set sorted [sortDictByValue $d1]

如果您有的话,-stride 选项会更容易使用。

关于sorting - 按值对 Tcl 字典排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5726938/

相关文章:

javascript - 对对象数组进行排序但忽略名称中的 'THE'

python列表到字典的数据流

tcl - 预期 Tcl 脚本 - 使用生成传递带引号的参数时出错

linux - 我无法从我的 Linux 系统中卸载 Tcl

c - 如何用C语言将两个字符串写入一个文件并对其进行排序?

arrays - k-最大元素优化 Swift 3.0

Python 字典 : the size affects timing?

compiler-errors - 如何在Ubuntu 17.10上编译WordNet-3.0?

sorting - 堆排序:为什么不使用 "Soft Heap"来提高性能?

python - 来自列表值字典的 Pandas 数据框