5

所以基本上我有这样的东西:

[a: ["c","d"], b: ["e","f"]]

每个列表中的项目数量是任意的。如果只有一项,则列表不再是列表,而是字符串。

我想把它变成:

[ [a:"c", b:"e"], [a:"d",b:"f"] ]

我真的不在乎解决方案是否使用 Groovy 方法。谢谢你的帮助!

4

4 回答 4

10

这是另一种方法,我认为它不那么晦涩,但仍然相当简洁:

def ml = [a: ["c","d"], b: ["e","f"]]

// Create an empty list that creates empty maps as needed
def lm = [].withDefault{ [:] }

ml.each{ k, values ->
    [values].flatten().eachWithIndex { value, index ->
        lm[index][k] = value
    }
}

assert lm == [[a:"c", b:"e"], [a:"d", b:"f"]]

如果您不想或不能使用withDefault(因为您不希望列表自动增长),那么这也可以:

def ml = [a: ["c","d"], b: ["e","f"]]

def lm = []

ml.each{ k, values ->
    [values].flatten().eachWithIndex { value, index ->
        lm[index] = lm[index] ?: [:]
        lm[index][k] = value
    }
}

assert lm == [[a:"c", b:"e"], [a:"d", b:"f"]]

编辑:添加代码来处理列表中不包含的字符串。

请注意,给定的技巧 ( [values].flatten().eachWithIndex{...}) 不一定非常有效。如果速度很重要,那么使用它会稍微快一些,但会牺牲可读性:

(values instanceof List ? values : [values]).eachWithIndex{...}
于 2013-03-22T22:30:47.030 回答
7

单线,假设 x =[a: ["c","d"], b: ["e","f"]]或 x = [a: "b", c: "d"]

[x*.key, x*.value].transpose()*.combinations().transpose()*.flatten()*.toSpreadMap()

这是如何工作的:

首先,拆分键和值:

[x*.key, x*.value]=[[a, b], [[c, d], [e, f]]]

转置它们以配对键和值:

[[a, b], [[c, d], [e, f]]].transpose()=[[a, [c, d]], [b, [e, f]]]

用于combinations将键与其值配对(此处使用扩展运算符将其应用于每个列表元素)。请注意,组合将同时处理[a:b][a:[b,c]]正确处理:

[[a, [c, d]], [b, [e, f]]]*.combinations()=[[[a, c], [a, d]], [[b, e], [b, f]]]

转置列表,以便我们以 abab 而不是 aabb 结束(尽管有些嵌套):

[[[a, c], [a, d]], [[b, e], [b, f]]].transpose()=[[[a, c], [b, e]], [[a, d], [b, f]]]

展平嵌套列表(再次使用 spread 来展平嵌套列表,但不是整个列表):

[[[a, c], [b, e]], [[a, d], [b, f]]]*.flatten()=[[a, c, b, e], [a, d, b, f]]

展开toSpreadMap以将此列表转换为地图列表。

[[a, c, b, e], [a, d, b, f]]*.toSpreadMap()=[*:[b:e, a:c], *:[b:f, a:d]]

于 2013-04-02T21:33:51.730 回答
2

定义一些函数:

// call a 2-element list a "pair"

// convert a map entry (where entry.value can be 
// a single string or a list of strings) into a list of pairs
def pairs(entry) {
  if (entry.value instanceof String)
    return [[entry.key, entry.value]]
  entry.value.collect { [entry.key, it]}
}

// convert list of pairs to a map
def toMap(pairs) {
  pairs.inject([:]){ m,i -> m[i[0]] = i[1]; m }
}

// kind of like transpose but doesn't stop with shortest list. 
// (would like to find a less ugly way of doing this)
def mytranspose(lists) {
  def retval = []
  def mx = lists.inject(0){x, i -> i.size() > x ? i.size() : x}
  for (int i = 0; i < mx; i++) {
    def row = []
    lists.each { lst ->
      if (lst.size() > i) row << lst[i]
    }
    retval << row
  }
  retval
}

然后把它放在一起并测试它:

groovy:000> m = [a: ["c","d"], b: ["e","f"]]
groovy:000> mytranspose(m.entrySet().collect{pairs(it)}).collect{toMap(it)}
===> [{a=c, b=e}, {a=d, b=f}]

作为字符串的映射条目可以工作,并且映射条目列表可以是不同的长度:

groovy:000> m['g'] = 'h'
===> h
groovy:000> m['x'] = ['s', 't', 'u', 'v']
===> [s, t, u, v]
groovy:000> m
===> {a=[c, d], b=[e, f], g=h, x=[s, t, u, v]}
groovy:000> mytranspose(m.entrySet().collect{pairs(it)}).collect{toMap(it)}
===> [{a=c, b=e, g=h, x=s}, {a=d, b=f, x=t}, {x=u}, {x=v}]
于 2013-03-22T21:43:43.440 回答
1

这就是我最终要做的。如果有人有更好的解决方案,请告诉我,我会接受它作为答案。

  Map xyz = [a: ["c","d"], b: ["e","f"]]

  List result = []

    Closure updateMap = { list, index, key, value ->
        if ( !(list[index] instanceof Map) ) {
            list[index] = [:]
        }
        list[index]."$key" = value
    }

    xyz.each { k, v ->
        if (v instanceof ArrayList) {
            v.eachWithIndex { val, idx ->
                updateMap(result, idx, k, val)
            }
        }
        else {
            updateMap(result, 0, k, v)
        }
    }
于 2013-03-22T19:54:24.807 回答