tcl - 按预定义列表中的值对 TCL 列表进行排序

标签 tcl

实际上 C# 中存在一个问题,因此希望有人能给我 TCL 解决方案。 Sort a List based on a Pre-Sorted List

我有一个已经排序的列表。比如说,我的排序列表是

{"Junior Developer" "Developer" "Senior Developer" "Project Lead"}

现在,我想按照与上述列表相同的顺序对上述列表的任何子集进行排序。也就是说,如果我有输入

{"Developer" "Junior Developer"}

我想要输出为

{"Junior Developer" "Developer"}

如果输入的是

{"Project Lead" "Junior Developer" "Developer"}

然后我想要输出为

{"Junior Developer" "Developer" "Project Lead"}

我看到lsort有一个-command选项,但阅读了很多评论说它没有很好的性能,所以想知道是否还有另一种方法也许使用 dict 来保留顺序。

最佳答案

您可以使用lsearch将索引放入排序列表中,然后将它们用作排序规则键:

set orderList {"Junior Developer" "Developer" "Senior Developer" "Project Lead"}
set original {"Developer" "Junior Developer"}

set keyed [lmap value $original {list $value [lsearch -exact $orderList $value]}]
set sortedKeyed [lsort -index 1 -integer $keyed]
set sorted [lmap value $sortedKeyed {lindex $value 0}]

puts "$original -> $sorted"
# "Developer" "Junior Developer" -> {Junior Developer} Developer

不建议在输出中使用双引号将值引起来;它不是规范的列表引用样式(并且很难强制 Tcl 这样做;在执行用户可见的输出时,存在一些邪恶的边缘情况通常并不重要)。


您可以使用 lsort-indices 选项来避免构建所有这些元组。

set orderList {"Junior Developer" "Developer" "Senior Developer" "Project Lead"}
set original {"Developer" "Junior Developer"}

set indexes [lmap value $original {lsearch -exact $orderList $value}]
set sortedIndexes [lsort -indices -integer $indexes]
set sorted [lmap idx $sortedIndexes {lindex $original $idx}]

puts "$original -> $sorted"
# "Developer" "Junior Developer" -> {Junior Developer} Developer

你可以使用foreach代替lmap,但是代码比较冗长。

关于tcl - 按预定义列表中的值对 TCL 列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58736077/

相关文章:

regex - 如何使用正则表达式提取数字中的单个数字

if-statement - 下面的 tcl 代码会做什么?

tcl - 如何通过生成的telnet session 发送转义字符^]?

c - 在 C 头文件 tclPlatDecls.h 中,TclPlatStubHooks 在哪里定义?

windows - 在 tcl 中计算 proc 内的命令?

numbers - 如何用零填充数字到 tcl 中的特定长度?

linux - 可以期望产生一个 bash 函数吗?

bash - 在退出脚本之前等待后台进程完成

regex - 在 tcl 中的正则表达式中传递变量

c++ - VTK如何平滑一条线