Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Connecting strings in a element without using double for loops Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading