问题描述
致电时
sorted(<#source: C#>, <#isOrderedBefore: (C.Generator.Element, C.Generator.Element) -> Bool##(C.Generator.Element, C.Generator.Element) -> Bool#>)
您可以通过$0
和$1
访问两个源元素进行比较.但是,如何确定从源中获取索引的索引呢?
you can access the two source elements for comparison via $0
and $1
. But how can I determine the index from where they were taken from the source?
推荐答案
您可以将sorted
传递给sorted
,而不是元素的集合,而是元素的索引:
You could pass into sorted
not a collection of elements, but the indices of the elements:
let a = ["hello","i","must","be","going"]
let idxs = sorted(indices(a)) { a[$0] < a[$1] }
// produces [3, 4, 0, 1, 2]
或者,如果您不喜欢捕获a
并希望将元素本身传递到闭包中,则可以传递一系列的索引和元素对,如下所示:
Or, if you don't like capturing a
and wanted the elements themselves passed into the closure, you could pass in a sequence of pairs of the index and the element, like so:
let pairs = sorted(Zip2(indices(a),a)) {
$0.1 < $1.1
}
请注意,结果将是(index,element)
对的数组:[(3, be), (4, going), (0, hello), (1, i), (2, must)]
.如果您只想将其转换为元素,可以执行map(pairs) { $0.1 }
Note the result would be an array of (index,element)
pairs: [(3, be), (4, going), (0, hello), (1, i), (2, must)]
. If you wanted to turn that back into just the elements, you can do map(pairs) { $0.1 }
此外,如果您选择了正义指数路线,并希望以后再将其转换为元素,则可以使用PermutationGenerator
做到这一点:
Also, if you take the just-indices route and want to turn that back into elements later, you can do it with PermutationGenerator
:
let values = PermutationGenerator(elements: a, indices: idxs)
println(" ".join(values)) // prints "be going hello i must"
这篇关于sorted()中元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!