How to know the indices of values in collection [closed]

孤街浪徒 提交于 2020-01-06 12:39:54

问题


Referring to this question: How to subtract dates from each other

In Groovy, I've got a script that spits out the 5 largest values from a text file collection. How can I know what the indices of those values are?


回答1:


If you have a list of things ie:

def list = [ 'c', 'a', 'b' ]

One way of knowing the original index would be to use transpose() to join this list to a counter, then sort the new list, then you will have a sorted list with the original index as the secondary element

ie:

[list,0..<list.size()].transpose().sort { it[0] }.each { item, index ->
  println "$item (was at position $index)"
}

To break that down;

[list,0..<list.size()]

gives us (effectively) a new list [ [ 'c', 'a', 'b' ], [ 0, 1, 2 ] ]

calling transpose() on this gives us: [ [ 'c', 0 ], [ 'a', 1 ], [ 'b', 2 ] ]

We then sort the list based on the first item in each element (the letters from our original list) with sort { it[0] }

And then iterate through each, printing out our now sorted item, and its original index location




回答2:


If the values are unique, you might just use the indexof method over the original list. For example, if you have the list:

def list = [4, 8, 0, 2, 9, 5, 7, 3, 6, 1]

And you know how to get the 5 largest values:

def maxVals = list.sort(false, {-it}).take 5 // This list will be [9, 8, 7, 6, 5]

You can then do:

def indexes = maxVals.collect { list.indexOf it }
println indexes

And it will print:

[4, 1, 6, 8, 5]


来源:https://stackoverflow.com/questions/8087873/how-to-know-the-indices-of-values-in-collection

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