如何使用dart中的所有元素将2d列表转换为1d列表?
我有这个2d列表:
List<List<int>> list2d = [[1, 2], [3, 4]];
我想要的是:
List<int> list1d = [1, 2, 3, 4];
通过将第一个(2d)转换为第二个(1d),但不编写任何(for/while)循环代码,如果有任何内置方法,如map()/where()/cast()/...etc
。
有什么想法吗?
发布于 2020-11-26 06:11:06
正如其他人所指出的那样,expand
可以做您想做的事情
var list2d = [[1, 2], [3, 4]];
var list1d = list2d.expand((x) => x).toList();
您也可以,也许最好是使用列表文字:
var list1d = [for (var list in list2d) ...list];
一般来说,iterable.expand((x) => e).toList()
等同于[for (var x in iterable) ...e]
。
发布于 2020-11-26 03:34:38
只需像这样使用reduce
函数:
List<int> list1d = list2d.reduce((value, element) {
value.addAll(element);
return value;
});
定义:
List<T> reduce(List<T> Function(List<T>, List<T>) combine);
发布于 2020-11-26 03:49:35
您可以只使用.expand
方法:
List<int> list1d = list2d.expand((e) => e).toList();
https://stackoverflow.com/questions/65011588
复制相似问题