2

如何从数组数组中获取列表?

我有一个列表列表,例如:[[1,2,3],[1,2,3],[1,2,3]].

我想要一个包含列表中所有第一个元素的列表。

例如,在我的示例中,我想要一个list = [1,1,1].

4

2 回答 2

6

如果您还可能想要获取每个列表的第二个/第三个元素,您还可以使用transpose

def input = [[1,2,3],[1,2,3],[1,2,3]]
def output = input.transpose()

// All the lists are joined by element index
assert output == [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

// Grab the first one (1,1,1)
assert output[ 0 ] == [ 1,1,1 ]
于 2013-09-05T12:40:33.397 回答
5

如果你知道你总是有一个列表列表(即内部列表总是存在),你可以这样做:

def lists = [[1,2,3],[1,2,3],[1,2,3]]
def result = lists.collect { it[0] }
assert result == [1,1,1]
于 2013-09-05T12:26:40.630 回答