当列表中有多个元素时查找元素的索引
Find index of an element when there are multiples of the element in a list
我有一个列表是这样写的:
def availFood = ["${property['Cake']}", "${property['Custard']}", "${property['Donuts']}"]
当我们打印那个列表时,它看起来像这样:
[true, true, false]
我想说的是“对于每个真实值,做一堆事情”。我是这样做的:
for(currentFood in availFood){
if (currentFood == "true"{
//Find out the index of the current food to figure out which one it was
def foodNum = availFood.indexOf(currentFood)
def foodName = ""
//a big if statement for 0 = "Cake", 1 = "Custard", 2 = "Donuts"
println("Our current food is ${foodName}!")
}
}
但是 .indexOf 将 return 匹配 currentFood 的第一个值的索引,而不是元素 currentFood 的索引。意思是因为索引 1 和 2 都为真,availFood.indexOf(currentFood)
将始终 return 1
这将给我错误的 foodName。
我该如何解决这个问题?
要执行您真正想要的操作,惯用代码可能如下所示:
def property = [ Custard:true, Donuts:true ] // fake out your property
def availFood = [ 'Cake', 'Custard', 'Donuts' ]
availFood.eachWithIndex{ foodName, foodNum ->
if( !property[ foodName ] ) return
println "Our current food is $foodName / $foodNum!"
}
打印
Our current food is Custard / 1!
Our current food is Donuts / 2!
我有一个列表是这样写的:
def availFood = ["${property['Cake']}", "${property['Custard']}", "${property['Donuts']}"]
当我们打印那个列表时,它看起来像这样:
[true, true, false]
我想说的是“对于每个真实值,做一堆事情”。我是这样做的:
for(currentFood in availFood){
if (currentFood == "true"{
//Find out the index of the current food to figure out which one it was
def foodNum = availFood.indexOf(currentFood)
def foodName = ""
//a big if statement for 0 = "Cake", 1 = "Custard", 2 = "Donuts"
println("Our current food is ${foodName}!")
}
}
但是 .indexOf 将 return 匹配 currentFood 的第一个值的索引,而不是元素 currentFood 的索引。意思是因为索引 1 和 2 都为真,availFood.indexOf(currentFood)
将始终 return 1
这将给我错误的 foodName。
我该如何解决这个问题?
要执行您真正想要的操作,惯用代码可能如下所示:
def property = [ Custard:true, Donuts:true ] // fake out your property
def availFood = [ 'Cake', 'Custard', 'Donuts' ]
availFood.eachWithIndex{ foodName, foodNum ->
if( !property[ foodName ] ) return
println "Our current food is $foodName / $foodNum!"
}
打印
Our current food is Custard / 1!
Our current food is Donuts / 2!