I'm trying to convert map
Python function into Groovy equivalent.
def check(parameters_list, parameter):
if parameter in parameters_list:
return 1
else:
return 0
par_list_1 = [‘a’, ‘b’, ‘c’]
par_1 = ‘a’
par_list_2 = [‘a’, ‘b’, ‘c’]
par_2 = ‘b’
par_list_3 = [‘a’, ‘b’, ‘c’]
par_3 = ‘d’
result = list(map(check, [par_list_1, par_list_2, par_list_3], [par_1, par_2, par_3]))
print(result)
This code should return [1,1,0]
.
CodePudding user response:
You can use a list comprehension instead of map.
pars = {
'a': ['a','b','c'],
'b': ['a','b','c'],
'd': ['a','b','c'],
}
result = [1 if k in v else 0 for k,v in pars.items()]
print(result)
CodePudding user response:
A Groovy approach that is structurally similar to what you are starting with is the following:
check = { parameterList, parameter ->
parameter in parameterList ? 1 : 0
}
par_list_1 = ['a', 'b', 'c']
par_1 = 'a'
par_list_2 = ['a', 'b', 'c']
par_2 = 'b'
par_list_3 = ['a', 'b', 'c']
par_3 = 'd'
result = [[par_list_1, par_1],[par_list_2, par_2],[par_list_3, par_3]].collect {
check(*it)
}
CodePudding user response:
your original python code in groovy:
def check={parameters_list, parameter->
if(parameter in parameters_list) return 1
else return 0
}
def par_list_1 = ['a', 'b', 'c']
def par_1 = 'a'
def par_list_2 = ['a', 'b', 'c']
def par_2 = 'b'
def par_list_3 = ['a', 'b', 'c']
def par_3 = 'd'
def result = [
[par_list_1, par_list_2, par_list_3],
[par_1, par_2, par_3]
].transpose().collect(check)
println(result)
the same but simplified like in mama's answer
def pars = [
['a', ['a','b','c']],
['b', ['a','b','c']],
['d', ['a','b','c']],
]
def result = pars.collect{ p, p_list-> p in p_list ? 1 : 0 }
println(result)
links:
http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/List.html#transpose()