Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting 排序两个索引相同的列表_Sorting_Tcl_Tclsh - Fatal编程技术网

Sorting 排序两个索引相同的列表

Sorting 排序两个索引相同的列表,sorting,tcl,tclsh,Sorting,Tcl,Tclsh,我是tcl的新手。我需要对值列表进行排序并保存索引。 我有两个列表,我想对listA排序,但我想对listB排序,保留listA的索引 例如: set listA {5 6 7 3 4 7 8 9} set listB {0 1 2 3 4 5 6 7} set sort_listA [lsort $listA] 现在,sort_listA将是3 4 5 6 7 8 9 我想排序listBlist,保持与sort\u listA相同的索引,如: 3 4 0 1 2 5 6 7 换句话说,我需

我是tcl的新手。我需要对值列表进行排序并保存索引。 我有两个列表,我想对listA排序,但我想对listB排序,保留listA的索引

例如:

set listA {5 6 7 3 4 7 8 9}
set listB {0 1 2 3 4 5 6 7}

set sort_listA [lsort $listA]
现在,
sort_listA
将是
3 4 5 6 7 8 9

我想排序
listB
list,保持与
sort\u listA
相同的索引,如:

3 4 0 1 2 5 6 7

换句话说,我需要使用
listA
的排序对两个列表进行排序。
有人能帮我吗?

这正是
lsort
具有
-index
选项(需要8.5或更高版本)的任务类型。它不是排序值列表,而是将索引列表返回到原始列表中,按照您检索它们以获得排序列表的顺序,这非常适合您的任务。这个交互式会话(在Tcl 8.6中,因此我使用了
lmap
)表示:

% set listA {5 6 7 3 4 7 8 9}
5 6 7 3 4 7 8 9
% set listB {0 1 2 3 4 5 6 7}
0 1 2 3 4 5 6 7
% set idxs [lsort -indices $listA]
3 4 0 1 2 5 6 7
% lmap i $idxs {lindex $listA $i}
3 4 5 6 7 7 8 9
% lmap i $idxs {lindex $listB $i}
3 4 0 1 2 5 6 7

如果您仍然使用8.5,则可以使用
foreach
进行重新映射;通过以下步骤更容易:

proc mapindices {indexlist valuelist} {
    set result {}
    foreach i $indexlist {
        lappend result [lindex $valuelist $i]
    }
    return $result
}
set listA {5 6 7 3 4 7 8 9}
set listB {0 1 2 3 4 5 6 7}
puts [mapindices [lsort -indices $listA] $listB]
现在,在8.4(不再支持!)中没有索引选项,因此需要做更多的工作

proc lsortIndices {list} {
    # Pair each value up with its index
    set zipped {}
    set idx -1
    foreach val $list {
        lappend zipped [list [incr idx] $val]
    }

    # Do the sorting by the value of the pair
    set sorted [lsort -index 1 $zipped]

    # Unpack the indices from the pairs to get the result
    set result {}
    foreach pair $sorted {
        lappend result [lindex $pair 0]
    }
    return $result
}
但是,此时您可能只需将这两个列表压缩在一起,并更直接地工作:

set zipped {}
foreach valA $listA valB $listB {
    lappend zipped [list $valA $valB]
}

set sorted [lsort -index 0 $zipped]

set listAsorted {}
set listBsorted {}
foreach pair $sorted {
    lappend listAsorted [lindex $pair 0]
    lappend listBsorted [lindex $pair 1]
}
使用Tcl 8.4以上的旧版本需要使用
-command
选项,这非常慢