nancy
nancy

Reputation: 175

Union with tuples Python

import itertools

list_with_tuples=[(1,), (2,), (3,)]
pairs = itertools.combinations(list_with_tuples, 2)
for pair in pairs:
   print(pair)

so the result of pairs is :

 ((1,),(2,)) ,

 ((1,),(3)) ,

 ((2,),(3,))

How I can union them? After union I want to do a dictionary like:

di={ (1,2): value1, (1,3): value2, (2,3): value3 }

How can I do this?

Upvotes: 9

Views: 8301

Answers (4)

wim
wim

Reputation: 362756

One way to "union" tuples in python is to simply add them:

>>> (1,) + (2,)
(1, 2)

So you can modify your example to add:

import itertools

list_with_tuples=[(1,), (2,), (3,)]
pairs = itertools.combinations(list_with_tuples, 2)
for left, right in pairs:
     print(left + right)

Outputs:

(1, 2)
(1, 3)
(2, 3)

If you need to add n tuples, rather than just 2 of them, you can use sum and specify an initial value of the empty tuple () as the second argument.

Alternatively, as Kevin mentioned in the comments, you can build a new tuple by consuming the output of an itertools.chain, which will likely be more efficient if n is large.

Upvotes: 11

Kevin
Kevin

Reputation: 30151

You can join iterable objects such as tuples and lists together using itertools.chain():

list_with_tuples=[(1,), (2,), (3,)]
pairs = itertools.combinations(list_with_tuples, 2)
for pair in pairs:
    print(tuple(itertools.chain(*pair)))

This also has the advantage of being lazy, so you can iterate over the chain one element at a time instead of making a full tuple out of it, if that's what you need. If pair is also a lazy iterator, you probably want to use itertools.chain.from_iterable() instead of the star operator.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You can chain the elements into a single tuple:

from itertools import chain,combinations
list_with_tuples=[(1,), (2,), (3,)]


di =  {tuple(chain.from_iterable(comb)):"value" for comb in combinations(list_with_tuples, 2)}

print(di)
{(1, 2): 'value', (1, 3): 'value', (2, 3): 'value'}

It will work for any length combinations.

If you have a another container that has the values you can zip:

from itertools import chain,combinations
list_with_tuples=[(1,), (2,), (3,)]

values = [1,2,3]
di = {tuple(chain.from_iterable(comb)): val for comb,val in zip(combinations(list_with_tuples, 2),values)}

print(di)
{(1, 2): 1, (1, 3): 2, (2, 3): 3}

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117876

You can use a dict comprehension to do this for you. Iterate over the itertools.combinations, index out the values from the tuple, then create your new tuple as the key and add them for the value.

>>> {(i[0],j[0]) : i[0] + j[0] for i,j in itertools.combinations(list_with_tuples, 2)}
{(1, 2): 3, (1, 3): 4, (2, 3): 5}

Upvotes: 0

Related Questions