Python tuple union

import itertools

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

therefore, the result of the pair is:

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

 ((1,),(3)) ,

 ((2,),(3,))

How can I combine them? After combining, I want to make a dictionary like:

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

How can i do this?

+4
source share
4 answers

One way to “merge” tuples in python is to simply add them:

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

So you can change 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 tuples n, and not just 2 of them, you can use sumand specify the initial value of the empty tuple ()as the second argument.

Alternatively, as Kevin noted in the comments, you can build a new tuple by consuming output itertools.chain, which is more likely to be more effective if nlarge.

+7

dict, . itertools.combinations, tuple, tuple .

>>> {(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}
0

You can chain elements into one 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 another container that matters, you can pin:

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}
0
source

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 a chain one element at a time, instead of making it a full tuple from it if you need it. If pairit is also a lazy iterator, you probably want to use itertools.chain.from_iterable()stars instead of the operator.

0
source

Source: https://habr.com/ru/post/1589031/


All Articles