如何知道集合中的值的索引 [英] How to know the indices of values in collection

查看:249
本文介绍了如何知道集合中的值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用此问题:如何从每个日历中减去日期其他

在Groovy中,我有一个脚本从文本文件集合中输出5个最大值。

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?

推荐答案

如果你有一个列表的东西ie:

If you have a list of things ie:

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

了解原始索引的一种方法是使用 transpose()将此列表加入计数器,然后对新列表进行排序,那么您将具有原始索引作为辅助元素的排序列表。

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

即:

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

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

为我们提供了一个新的列表 [['c','a','b'] ,[0,1,2]]

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

调用 transpose()给我们: [['c',0],['a',1],['b',2]]

然后,我们基于每个元素(来自我们的原始列表中的字母)的第一个项目对列表排序 sort {it [0]}

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

这篇关于如何知道集合中的值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆