[英]How best to get map from key list/value list in groovy?
In python, I can do the following: 在python中,我可以执行以下操作:
keys = [1, 2, 3]
values = ['a', 'b', 'c']
d = dict(zip(keys, values))
assert d == {1: 'a', 2: 'b', 3: 'c'}
Is there a nice way to construct a map in groovy, starting from a list of keys and a list of values? 有没有一种很好的方法来构建一个groovy中的地图,从一个键列表和一个值列表开始?
There's also the collectEntries
function in Groovy 1.8 Groovy 1.8中还有
collectEntries
函数
def keys = [1, 2, 3]
def values = ['a', 'b', 'c']
[keys,values].transpose().collectEntries { it }
Try this: 试试这个:
def keys = [1, 2, 3]
def values = ['a', 'b', 'c']
def pairs = [keys, values].transpose()
def map = [:]
pairs.each{ k, v -> map[k] = v }
println map
Alternatively: 或者:
def map = [:]
pairs.each{ map << (it as MapEntry) }
There isn't anything built directly in to groovy, but there are a number of ways to solve it easily, here's one: 没有任何东西直接构建到groovy,但有很多方法可以轻松解决它,这里是一个:
def zip(keys, values) {
keys.inject([:]) { m, k -> m[k] = values[m.size()]; m }
}
def result = zip([1, 2, 3], ['a', 'b', 'c'])
assert result == [1: 'a', 2: 'b', 3: 'c']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.