如何在Dart中合并2个列表? [英] How to merge 2 lists in Dart?
本文介绍了如何在Dart中合并2个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试合并2个列表,因此输出如下:
I'm trying to merge 2 lists so the output is the following:
List<String> array1 = ["John", "Bob", "Fred", "June", "Tom"];
List<String> array2 = ["House", "Flat", "Bungalow"];
List<String> output = //["John", "House", "Bob", "Flat", "Fred", "Bungalow", "June", "Tom"]
如何实现?我看了颤抖库中的 zip 函数
How can I achieve this? I've had a look at the zip function in the quiver library but it only returns a list as long as the shortest list that's passed into it.
EDIT :为澄清起见,我本质上想做的是与zip函数相同,但是如果一个数组比另一个数组长,我只想将剩余的项追加到末尾。
EDIT: To clarify, I essentially want to do the same as the zip function but if one array is longer than the other, I just want to append the left over items on to the end.
推荐答案
我不知道可以使用的任何东西,但这应该可以做您想要的:
I don't know anything ready-to-use, but this should do what you want:
import 'dart:math' as math;
void main() {
List<String> array1 = ["John", "Bob", "Fred", "June", "Tom"];
List<String> array2 = ["House", "Flat", "Bungalow"];
List<String> output = List<String>(array1.length + array2.length);
int i = 0;
for (i; i < math.min(array1.length, array2.length); i++) {
output[i * 2] = array1[i];
output[i * 2 + 1] = array2[i];
}
print(output);
if (array1.length != array2.length) {
if (array1.length > array2.length) {
output.setRange(i * 2, output.length, array1.sublist(i));
} else {
output.setRange(i * 2, output.length, array2.sublist(i));
}
}
print(output);
}
这篇关于如何在Dart中合并2个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文