Index of element in sorted()

 ̄綄美尐妖づ 提交于 2019-12-02 11:19:16

问题


When you call

sorted(<#source: C#>, <#isOrderedBefore: (C.Generator.Element, C.Generator.Element) -> Bool##(C.Generator.Element, C.Generator.Element) -> Bool#>)

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?


回答1:


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]

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
}

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 }

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"


来源:https://stackoverflow.com/questions/27695529/index-of-element-in-sorted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!