1

I have a list with nested lists of different lengths ranging from 3 to 105. I want to create based on that new lists that contain a combination of all pairs in these original list following the format: from [7,5,6] to [7,5], [7,6], [5,6]

I used the code below, but this is not feasible with 105 values in a list. Is there an algorithm that can automate this process?

list3 = ([7,5,6], [6,9,7], [7,8,4], [2,4,6,7,9])
list4 = []
for sublist in list3:
    if len(sublist) == 3:
       list4.append([sublist[0], sublist[1])
       list4.append([sublist[0], sublist[2])
       list4.append([sublist[1], sublist[2])

1 Answers1

1

You could perhaps use itertools.combinations() to help generate unique sets of pairs given a maximum range.

Something like:

from itertools import combinations
list3 = ([7,5,6], [6,9,7], [7,8,4], [2,4,6,7,9])
list4 = []
for sublist in list3:
    for (i, j) in combinations(range(len(sublist)), 2):
       list4.append([sublist[i], sublist[j]])

To make this more efficient, I would recommend using a list comprehension:

list4 = [[sublist[i], sublist[j]] for sublist in list3 for (i, j) in combinations(range(len(sublist)), 2)]

More on list comprehensions versus appending to lists using for loops here: Why is a list comprehension so much faster than appending to a list?


As noted by @chepner in his comment below, combinations takes in any iterable, so you can simply use that as input into combinations. We also don't need to append individual elements. We can generate the combinations we need which will generate a list, and we can just concatenate everything together:

list4 = [t for sublist in list3 for t in combinations(sublist, 2)]
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • @DeveshKumarSingh Thanks. Was about to correct that. – rayryeng Jun 18 '19 at 17:57
  • 1
    You can generate the combinations from the sublist directly, as well as replacing the entire inner loop with `list4.extend(combinations(sublist, 2))` – chepner Jun 18 '19 at 18:05
  • Then go one step further can define `list4` with a list comprehension: `list4 = [t for sublist in list3 for t in combinations(sublist, 2)]`. – chepner Jun 18 '19 at 18:07
  • @chepner I appreciate the feedback. I've edited the post. Thank you! – rayryeng Jun 18 '19 at 18:09
  • 1
    @rayryeng thank you for your post, this method worked perfectly. – Rit Chatterjee Jun 18 '19 at 18:53
  • @RitChatterjee you're very welcome. If you have no more issues, please go ahead and accept my answer. It signals to the community that you no longer need help. That's done by clicking on the checkmark icon underneath the up and down arrows to the top left of my answer. Good luck! – rayryeng Jun 18 '19 at 23:11