Split a list of tuples into sub-lists of the same tuple field [duplicate]

Use itertools.groupby: import itertools import operator data=[(1, ‘A’, ‘foo’), (2, ‘A’, ‘bar’), (100, ‘A’, ‘foo-bar’), (‘xx’, ‘B’, ‘foobar’), (‘yy’, ‘B’, ‘foo’), (1000, ‘C’, ‘py’), (200, ‘C’, ‘foo’), ] for key,group in itertools.groupby(data,operator.itemgetter(1)): print(list(group)) yields [(1, ‘A’, ‘foo’), (2, ‘A’, ‘bar’), (100, ‘A’, ‘foo-bar’)] [(‘xx’, ‘B’, ‘foobar’), (‘yy’, ‘B’, ‘foo’)] [(1000, ‘C’, ‘py’), (200, ‘C’, ‘foo’)] … Read more

How to sum elements at the same index in array of arrays into a single array?

You can use Array.prototype.reduce() in combination with Array.prototype.forEach(). var array = [ [0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3] ], result = array.reduce(function (r, a) { a.forEach(function (b, i) { r[i] = (r[i] || 0) + b; }); return r; }, []); document.write(‘<pre>’ + JSON.stringify(result, 0, 4) + ‘</pre>’); Update, … Read more

Creating sublists [duplicate]

Such a list of lists could be constructed using a list comprehension: In [17]: seq=[1,2,3,4,5,6,7,8] In [18]: [seq[i:i+3] for i in range(0,len(seq),3)] Out[18]: [[1, 2, 3], [4, 5, 6], [7, 8]] There is also the grouper idiom: In [19]: import itertools In [20]: list(itertools.izip_longest(*[iter(seq)]*3)) Out[20]: [(1, 2, 3), (4, 5, 6), (7, 8, None)] but … Read more

Mongodb aggregation pipeline how to limit a group push

Suppose the bottom left coordinates and the upper right coordinates are respectively [0, 0] and [100, 100]. From MongoDB 3.2 you can use the $slice operator to return a subset of an array which is what you want. db.collection.aggregate([ { “$match”: { “loc”: { “$geoWithin”: { “$box”: [ [0, 0], [100, 100] ] } }} … Read more

Group array values based on key in php? [duplicate]

You could use a generic function: function _group_by($array, $key) { $return = array(); foreach($array as $val) { $return[$val[$key]][] = $val; } return $return; } I added some sample code to test <?php $list= [ [ ‘No’ => 101, ‘Paper_id’ => ‘WE3P-1’, ‘Title’ => “a1”, ‘Author’ => ‘ABC’, ‘Aff_list’ => “University of South Florida, Tampa, United … Read more