Flatten an irregular (arbitrarily nested) list of lists

Using generator functions can make your example easier to read and improve performance. Python 2 Using the Iterable ABC added in 2.6: from collections import Iterable def flatten(xs): for x in xs: if isinstance(x, Iterable) and not isinstance(x, basestring): for item in flatten(x): yield item else: yield x Python 3 In Python 3, basestring is … Read more

Transpose and flatten two-dimensional indexed array where rows may not be of equal length

$data = array( 0 => array( 0 => ‘1’, 1 => ‘a’, 2 => ‘3’, 3 => ‘c’, ), 1 => array( 0 => ‘2’, 1 => ‘b’, ), ); $newArray = array(); $mi = new MultipleIterator(MultipleIterator::MIT_NEED_ANY); $mi->attachIterator(new ArrayIterator($data[0])); $mi->attachIterator(new ArrayIterator($data[1])); foreach($mi as $details) { $newArray = array_merge( $newArray, array_filter($details) ); } var_dump($newArray);

flattening nested Json in pandas data frame

If you are looking for a more general way to unfold multiple hierarchies from a json you can use recursion and list comprehension to reshape your data. One alternative is presented below: def flatten_json(nested_json, exclude=[”]): “””Flatten json object with nested keys into a single level. Args: nested_json: A nested json object. exclude: Keys to exclude … Read more

JavaScript flattening an array of arrays of objects

You can use Array.concat like bellow:- var arr = [[‘object1’, ‘object2’],[‘object1’],[‘object1′,’object2′,’object3’]]; var flattened = [].concat.apply([],arr); flattened will be your expected array. ES 2020 gives the flat, also flatMap if you want to iterate over, to flat lists of lists: [[‘object1’], [‘object2’]].flat() // [‘object1’, ‘object2’]