After performing some algorithm(s), I end up with a list similar to the one below:
l = Set([(integer_4_digits, integer_n_digits], ..)
ex: l = Set([(1011, 123556), (1041, 424553), (1241, 464096), (1027, 589325), (1011, 432341), (1031, 423076)])
l = list(l) #all tuples must exist once. need to get items by index to match (perhaps?)
Each tuple in this list has its first item a 4 digit integer (positive) and the second one, another positive integer.
What I want is:
To create a new list (of lists or tuples) where all the possible combinations are grouped together (in a list or a tuple) with cross matching, including a fifth (or 3rd, if it’s tuple+tuple+bool) element which is either True or False depending on whether or not if the first 4 digit integer of two newly matched-crossed tuples are the same or not (ex: 1011 == 1011 so Bool=True).
So after this process I want to get something like:
new_list = [(l[0], l[1], False), (l[0], l[2], False), (l[0], l[3], False), (l[0], l[4], True) ..
(l[1], l[2], False), (l[1], l[3], False), (l[1], l[4], False), ..
(l[2], l[3], False), (l[2], l[4], False), (l[2], l[5], False), ..]
As you can see, new_list does not contain duplicates matches. (l[0] is matched to l[1] only once, does not matter if the match tuple is a to be or b to a (l[0],l[1],..) or (l[1],l[0],..)
Now I can achieve this using nested for e in l loops and popping last e element and performing e[0] checks for bool and creating a new tuple (or list) and adding to the new_list list.
So how can I do this? How should I do it?
Use
itertools.combinations(); it creates the combinations you are looking for. Together with a list comprehension, you should be set:Note that the
Settype was made a built-in native type in python; just useset(lowercase) for the native version. We don’t need to turn the set into a list for this to work; itertools doesn’t care either way. You can even use the new{elem, elem, elem}set literal syntax.This produces: