Renklauf
Renklauf

Reputation: 981

From a combination, get subsets with members containing the same first element, python

Suppose I have the following list:

 ls = ['a', 'b', 'c', 'd']

I get a combination using

 list(itertools.combinations(iterable, 2))  

 >>> [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

What I'd like to do is break this combination into subsets, such that the first member of each tuple in the subset is the same:

 subset1: [('a', 'b'), ('a', 'c'), ('a', 'd')]
 subset2: [('b', 'c'), ('b', 'd'), 
 subset3: [('c', 'd')]

Any ideas?

Upvotes: 0

Views: 135

Answers (3)

Wairton de Abreu
Wairton de Abreu

Reputation: 1

try this:

[filter(lambda k:k[0]==p,comb) for p in ls]

where:

ls = ['a', 'b', 'c', 'd']

comb = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

the output is:

[[('a', 'b'), ('a', 'c'), ('a', 'd')], [('b', 'c'), ('b', 'd')], [('c', 'd')], []]

Upvotes: 0

mgilson
mgilson

Reputation: 310307

>>> import itertools as it
>>> ls = ['a', 'b', 'c', 'd']
>>> ii=it.groupby( it.combinations(ls, 2), lambda x: x[0] )
>>> for key, iterator in ii:
...     print key, list(iterator)
... 
a [('a', 'b'), ('a', 'c'), ('a', 'd')]
b [('b', 'c'), ('b', 'd')]
c [('c', 'd')]

If you don't like lambda, you could use operator.itemgetter(0) instead of lambda x: x[0].

Upvotes: 2

NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5243

subset = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
subsets = [[x for x in subset where x[0] == y] for y in ['a','b','c']]

Upvotes: 0

Related Questions