Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a List?

Tags:

dart

How can I easily flatten a List in Dart?

For example:

var a = [[1, 2, 3], ['a', 'b', 'c'], [true, false, true]]; var b = [1, 2, 3, 'a', 'b', 'c', true, false, true]; 

How do I turn a into b, i.e. into a single List containing all those values?

like image 400
Ahmed Avatar asked Mar 14 '13 15:03

Ahmed


People also ask

How do I flatten a list of lists in Python?

To flatten a list of lists in Python, use the numpy library, concatenate(), and flat() function. Numpy offers common operations, including concatenating regular 2D arrays row-wise or column-wise. We also use the flat attribute to get a 1D iterator over the array to achieve our goal.

How do you flatten a list of arrays?

You can flatten a NumPy array ndarray with the numpy. label() function, or the ravel() and flatten() methods of numpy.

How do you flatten data in Python?

The flatten() function is used to get a copy of an given array collapsed into one dimension. 'C' means to flatten in row-major (C-style) order. 'F' means to flatten in column-major (Fortran- style) order. 'A' means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.


2 Answers

The easiest way I know of is to use Iterable.expand() with an identity function. expand() takes each element of an Iterable, performs a function on it that returns an iterable (the "expand" part), and then concatenates the results. In other languages it may be known as flatMap.

So by using an identity function, expand will just concatenate the items. If you really want a List, then use toList().

var a = [[1, 2, 3], ['a', 'b', 'c'], [true, false, true]]; var flat = a.expand((i) => i).toList(); 
like image 198
Justin Fagnani Avatar answered Sep 23 '22 06:09

Justin Fagnani


I don't think there's a built-in method for that, but you can always reduce it to a single value:

var a = [[1, 2, 3], ['a', 'b', 'c'], [true, false, true]];  var flatten = a.reduce([], (p, e) {   p.addAll(e);   return p; });  print(flatten); 

I wish addAll() would return the original list. Currently it returns nothing. If that were true, you could write a single liner: a.reduce([], (p, e) => p.addAll(e)).

Alternatively, you can just loop through the list and add:

var flatten = []; a.forEach((e) => flatten.addAll(e)); 
like image 34
Kai Sellgren Avatar answered Sep 22 '22 06:09

Kai Sellgren