简体   繁体   English

如何从列表列表中获取列表

[英]How get a list from List of Lists

How get a list from array of arrays? 如何从数组数组中获取列表?

I have a List of Lists, like: [[1,2,3],[1,2,3],[1,2,3]] . 我有一个列表列表,如: [[1,2,3],[1,2,3],[1,2,3]]

I want to have a List that contains all first elements from my List. 我想要一个List,其中包含我列表中的所有第一个元素。

For example in my example, I want to have a list = [1,1,1] . 例如,在我的例子中,我想要一个list = [1,1,1]

If you also might want to get the second/third elements of each List, you can also use transpose : 如果您还想获得每个List的第二个/第三个元素,也可以使用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 ]

If you know you always have an list of lists (ie the inner list always exists), you could do it like this: 如果你知道你总是有一个列表列表(即内部列表总是存在),你可以这样做:

def lists = [[1,2,3],[1,2,3],[1,2,3]]
def result = lists.collect { it[0] }
assert result == [1,1,1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM