Groovy:从两个列表中创建新列表

时间:2013-10-09 11:03:13

标签: groovy

我是时髦的初学者

我有两个列表

    ​list1 = [[1,'Rob','Ben', 'Ni', 'cool'],[2,'Jack','Jo','Raj','Giri']....[]...] 

   list2 = [[null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12']]

我希望以下列格式组合这些列表

 list3  = [[1, null, '2013-10-09', '2013-10-10', 'Rob', 'Ben', 'Ni', 'cool'], [2, 4, '2013-10-11', '2013-10-12', 'Jack', 'Jo', 'Raj', 'Giri']]

尝试Groovy: Add some element of list to another list

但不能用这种格式帮助我!

5 个答案:

答案 0 :(得分:3)

您可以collect head()pop()tail()

def list1 = [ [1,'Rob','Ben', 'Ni', 'cool'], [2, 'Jack', 'Jo', 'Raj', 'Giri'] ]

def list2 = [ [null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12'] ]

def stack = list2.reverse()

def list3 = list1.collect { l1 -> 
    [l1.head()] + stack.pop() + l1.tail()
}

assert list3 == [
  [1, null, '2013-10-09', '2013-10-10', 'Rob', 'Ben', 'Ni', 'cool'], 
  [2,4,'2013-10-11', '2013-10-12', 'Jack', 'Jo', 'Raj', 'Giri']
]

答案 1 :(得分:1)

[list1, list2].transpose().collect { [it[0][0]] + it[1] + it[0][1..-1] }

会做你需要的但是不是特别有效,因为它创建然后扔掉许多中间列表。更有效的方法是良好的老式直接迭代:

def list3 = []
def it1 = list1.iterator()
def it2 = list2.iterator()
while(it1.hasNext() && it2.hasNext()) {
  def l1 = it1.next()
  def l2 = it2.next()
  def l = [l1[0]]
  l.addAll(l2)
  l.addAll(l1[1..-1])
  list3 << l
}

这不是Groovy,而是创建了更少的一次性列表。

答案 2 :(得分:1)

这是一种方式(显然需要对list1,list2,空列表等的匹配大小进行一些防御性检查):

def list1 = [[1,'Rob','Ben', 'Ni', 'cool'],[2,'Jack','Jo','Raj','Giri']] 
def list2 = [[null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12']]

def newList = []

list1.eachWithIndex { def subList1, def index ->
    def tmpList = []
    tmpList << subList1[0]
    tmpList.addAll(list2[index])
    tmpList.addAll(subList1[1..subList1.size()-1])
    newList << tmpList
}

def list3  = [[1, null, '2013-10-09', '2013-10-10', 'Rob', 'Ben', 'Ni', 'cool'], [2,4,'2013-10-11', '2013-10-12', 'Jack', 'Jo', 'Raj', 'Giri']]

assert newList == list3

答案 3 :(得分:1)

我更喜欢Will P的答案,但这里有另一种选择:

def list1 = [ [1,'Rob','Ben', 'Ni', 'cool'], [2, 'Jack', 'Jo', 'Raj', 'Giri'] ]

def list2 = [ [null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12'] ]

def list3 = []
list1.eachWithIndex { one, i -> list3 << [one[0]] + list2[i] + one[1..-1] }

assert list3 == [
  [1, null, '2013-10-09', '2013-10-10', 'Rob', 'Ben', 'Ni', 'cool'], 
  [2, 4,'2013-10-11', '2013-10-12', 'Jack', 'Jo', 'Raj', 'Giri']
]

答案 4 :(得分:0)

试试这个:

​list1 = [[1,'Rob','Ben', 'Ni', 'cool'],[2,'Jack','Jo','Raj','Giri']....[]...] 
list2 = [[null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12']]

def list3 = []
list3.addAll(list1)
list3.addAll(list2)