如何将map()用于多个列表?

时间:2018-11-05 15:15:33

标签: list dart flutter

我想得到这样的东西:

[list1, list2].map( (var1, var2) => do something with var1;
do something with var2)

我尝试过:

List<int> counts = [1,2,3];
List<String> strings = ['','2',''];
print([counts, strings].map((list) => list[0].isEven; list[1].lenght))

4 个答案:

答案 0 :(得分:2)

来自IterableZip

package:collection应该有所帮助。

https://pub.dartlang.org/documentation/collection/latest/collection/IterableZip-class.html

IterableZip([list1, list2]).map((values) {
    doSomethingWith(values[0]);
    doSomethingWith(values[2]);
});

答案 1 :(得分:0)

听起来https://pub.dartlang.org/documentation/async/latest/async/StreamZip-class.html是您想要的。

首先将list1list2转换成各自的流,然后使用StreamZip合并两个流。

例如,这会将两个值转换为包含两个值的字符串流:

StreamZip([list1, list2]).map((valuePair) => "${valuePair[0]}, ${valuePair[1]}"));

答案 2 :(得分:0)

听起来像您想要的zip函数,dart默认不提供。快速实施将是这样的:

List<T3> zipList<T1, T2, T3>(List<T1> l1, List<T2> l2, T3 Function(T1, T2) zipper) {
  if (l1.isEmpty) throw ArgumentError.value(l1, "l1", "input list cannot be empty");
  if (l1.length != l2.length) throw ArgumentError("Two lists must have the same length");
  var result = List<T3>(l1.length);
  for(var i = 0; i < l1.length; i++) {
    result.add(zipper(l1[i], l2[i]));
  }
  return result;
}

// here a quick example of how to use it.
class Bar {
  final int i;
  final String s;
  Bar(this.i, this.s);

  @override
  String toString() => "Bar: $i - $s";
}

void testZipList() {
  var list1 = [1,2,3];
  var list2 = ["", "2", ""];
  var bars = zipList(list1, list2, (l1, l2) => Bar(l1, l2));
  bars.forEach(print);
}

答案 3 :(得分:0)

除了已接受的答案中提供的zipList之外,这里还有一个listIterable,如果您拥有的可迭代项还不是列表,则可能会有用。

Iterable<T3> zipIterable<T1, T2, T3>(Iterable<T1> l1, Iterable<T2> l2, T3 Function(T1, T2) zipper) sync* {
  var i1 = l1.iterator;
  var i2 = l2.iterator;
  while(true) {
    var fin1 = !i1.moveNext();
    var fin2 = !i2.moveNext();
    if (fin1 != fin2) {
      throw ArgumentError("Two iterables must have the same length");
    }
    if (fin1) {
      return;
    }
    yield zipper(i1.current, i2.current);
  }
}