Home > Blockchain >  Is there a way in Dart using the list map method to build a list containing two (or more) items for
Is there a way in Dart using the list map method to build a list containing two (or more) items for

Time:06-02

In Python, this code realizes the objective:

intLst = [1, 2, 3]
f1 = lambda x: x
f2 = lambda x: x * 10
newLst = [f(x) for x in intLst for f in [f1, f2]]

print(newLst) # [1, 10, 2, 20, 3, 30]

but in Dart I was not able to do the same using an anonymous function passed to the map() List method.

CodePudding user response:

You can achieve the same thing using collection for, which allows you to do the same type of things you can do with a list comprehension in python.

void main() {
  List<int> intLst = [1, 2, 3];
  int Function(int) f1 = (x) => x;
  int Function(int) f2 = (x) => x * 10;
  List<int> newLst = [
    for (var x in intLst)
      for (var f in [f1, f2]) f(x),
  ];
  print(newLst); // [1, 10, 2, 20, 3, 30]
}

The alternative would be to use expand rather than map. expand is the same as what some other languages call flatMap.

void main() {
  List<int> intLst = [1, 2, 3];
  int Function(int) f1 = (x) => x;
  int Function(int) f2 = (x) => x * 10;
  List<int> newLst = intLst.expand((v) => [f1(v), f2(v)]).toList();
  print(newLst); // [1, 10, 2, 20, 3, 30]
}

CodePudding user response:

Here's another way to obtain the same result without using functions:

void main() {
  List<int> intList = [1, 2, 3];

  List<int> newList = [
    for (var x in intList) ...[x, x * 10, x * x],
  ];

  print(newList); // [1, 10, 1, 2, 20, 4, 3, 30, 9]
}
  •  Tags:  
  • dart
  • Related