2013-11-15 57 views
1

我的代碼:百分比常規列表切片

def originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] 

def newList = orginalList.percent(0.05,0.95) //I have no idea what I'm doing here 
println newList 

我有一個數字的原始名單,他們是1 - 100,我想打從原來的列表中選擇一個新的列表不過新名單隻能有數據屬於子範圍的原始列表的5% - 95%

所以新列表必須像[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18....95]。我怎麼做?我知道我的newList代碼是錯誤的

回答

3

你的意思是這樣的:

originalList[ 4..94 ] // zero starting pos 

或你需要的百分比?

你可以這樣做:

originalList[ (originalList.size() * 0.05 - 1)..<(originalList.size() * 0.95) ] 

您還可以使用元類:

List.metaClass.percent { double lower, double upper -> 
    int d = lower * delegate.size() - 1 
    int t = upper * delegate.size() 
    delegate.take(t).drop(d) 
} 

originalList.percent(0.05, 0.95)