-4

I need to generate every possible pairs in a list. For example

list=['1','2','3']

The end result that I want to have is

new_list=['1-2','1-3','2-1','2-3','3-1','3-2']

In my case, 1-2 != 2-1. Currently my code is

for x1 in b:
                for x2 in b:
                    if(x1==x2):
                        continue
                    else:
                        x3=x1+'-'+x2
                        new_list.append(x2)

As my actual data contains hundreds of list, is there any way to not use a double for loop?

Jas
  • 11
  • 3

2 Answers2

1

Use itertools:

import itertools

#to include pairs with same element (i.e. 1-1, 2-2 and 3-3)
>>> ["-".join(pair) for pair in itertools.product(lst, lst)]
['1-1', '1-2', '1-3', '2-1', '2-2', '2-3', '3-1', '3-2', '3-3']

#to exclude pairs with the same element
>>> ["-".join(pair) for pair in itertools.permutations(lst, 2)]
['1-2', '1-3', '2-1', '2-3', '3-1', '3-2']
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • For funtimes (read: mild performance benefits on CPython), you can use `list(map("-".join, itertools.permutations(lst, 2)))` (*maybe* `[f"{x}-{y}" for x, y in itertools.permutations(lst, 2)]`, not tested; f-strings slow things) to improve performance. Most C built-in iterators in CPython that produce `tuple`s have an optimization to reuse the same `tuple` over and over if all other references to it are released by the time the next output is requested. `map` releases the value it transforms before yielding it, enabling the optimization, as does unpacking the `tuple` in the `for` loop itself. – ShadowRanger Mar 11 '22 at 18:50
  • Also, minor side-note: It doesn't matter much here (saying `lst` twice isn't so bad), but for `product`, you can get the same result with `itertools.product(lst, repeat=2)` to get the same reuse of `lst` for both loops that behaves more like `permutations` does (it just has to be passed by keyword, because `product` can take multiple input iterables as positional arguments, and `repeat` must be keyword-only to differentiate). – ShadowRanger Mar 11 '22 at 18:53
0

You are finding the permutations of the list. For this, you can use:

from itertools import permutations
lst = ['1','2','3']
new_list = ["-".join(x) for x in permutations(lst, 2)]
print(new_list)

Output:

['1-2', '1-3', '2-1', '2-3', '3-1', '3-2']
Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27