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?
Operators can be used to concatenate or multiply tuples. Concatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple.
How to Perform the Union of Lists in Python? To perform the union of two lists in python, we just have to create an output list that should contain elements from both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the union of list1 and list2 will be [1,2,3,4,5,6,8,10,12] .
When it is required to concatenate multiple tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements.
The function “union()” is used to join two or more sets or lists. It is not compulsory that the given input must be a set. It can be any iterable object such as a list or tuple.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With