Replace list of list with “condensed” list of list while maintaining order

Here’s a brute-force approach (it might be easier to understand): from itertools import chain def condense(*lists): # remember original positions positions = {} for pos, item in enumerate(chain(*lists)): if item not in positions: positions[item] = pos # condense disregarding order sets = condense_sets(map(set, lists)) # restore order result = [sorted(s, key=positions.get) for s in sets] … Read more

How to turn an itertools “grouper” object into a list

The reason that your first approach doesn’t work is that the the groups get “consumed” when you create that list with list(groupby(“cccccaaaaatttttsssssss”)) To quote from the groupby docs The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous … Read more

N-D version of itertools.combinations in numpy

You can use itertools.combinations() to create the index array, and then use NumPy’s fancy indexing: import numpy as np from itertools import combinations, chain from scipy.special import comb def comb_index(n, k): count = comb(n, k, exact=True) index = np.fromiter(chain.from_iterable(combinations(range(n), k)), int, count=count*k) return index.reshape(-1, k) data = np.array([[1,2,3,4,5],[10,11,12,13,14]]) idx = comb_index(5, 3) print(data[:, idx]) output: … Read more

Powersets in Python using itertools

itertools functions return iterators, objects that produce results lazily, on demand. You could either loop over the object with a for loop, or turn the result into a list by calling list() on it: from itertools import chain, combinations def powerset(iterable): “powerset([1,2,3]) –> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)” s = list(iterable) return … Read more

itertools product speed up

The NumPy equivalent of itertools.product() is numpy.indices(), but it will only get you the product of ranges of the form 0,…,k-1: numpy.rollaxis(numpy.indices((2, 3, 3)), 0, 4) array([[[[0, 0, 0], [0, 0, 1], [0, 0, 2]], [[0, 1, 0], [0, 1, 1], [0, 1, 2]], [[0, 2, 0], [0, 2, 1], [0, 2, 2]]], [[[1, 0, … Read more