将 Python 映射函数转换为 Groovy 一个

Convert Python map function into Groovy one

我正在尝试将 map Python 函数转换为 Groovy 等效函数。

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)

这段代码应该return[1,1,0].

您可以使用列表理解而不是映射。

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)

您在 groovy 中的原始 python 代码:

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)

与妈妈的回答相同但简化了

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)

链接:

http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/List.html#transpose()

http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Iterable.html#collect(groovy.lang.Closure)

Groovy 结构类似于您开始使用的方法如下:

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)
}

它工作正常并且returns与上面的原始Python代码相同:

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'

pars = [[par_1, par_list_1],
        [par_2, par_list_2],
        [par_3, par_list_3]]


def result = pars.collect{ couple -> couple[0] in couple[1] ? 1 : 0 }

println(result)