我正在嘗試將mapPython 函式轉換為 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)
此代碼應回傳[1,1,0].
uj5u.com熱心網友回復:
您可以使用串列理解而不是地圖。
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)
uj5u.com熱心網友回復:
結構上與您開始使用的方法類似的 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)
}
uj5u.com熱心網友回復:
你在 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)
uj5u.com熱心網友回復:
它作業正常并回傳與上面原始 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386406.html
