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

Can't create pair of items from a list in a desired way

I’m trying to print the numbers from a list in such a way so that each number will pair with other numbers.

For example, if I consider this list ['SUB00879','REZ00682','DVP00464'], the following is how I’m expecting to print:

SUB00879 DVP00464
SUB00879 REZ00682
REZ00682 SUB00879
REZ00682 DVP00464
DVP00464 REZ00682
DVP00464 SUB00879

However, when I try like below:

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

folder_numbers = ['SUB00879','REZ00682','DVP00464']

for folder_num in folder_numbers:
    iteration = len(folder_numbers) -1
    for i in range(iteration):
        print(folder_num,folder_numbers[i])

I get output like (faulty):

SUB00879 REZ00682
SUB00879 DVP00464
REZ00682 REZ00682
REZ00682 DVP00464
DVP00464 REZ00682
DVP00464 DVP00464

How can I let the script print the output in the desired way?

>Solution :

You can use itertools.permutations() to generate the output you want, which is, as the name suggests, the n length permutations of the values in your array. n in your case is 2.

from itertools import permutations

folder_numbers = ['SUB00879','REZ00682','DVP00464']

permutations = list(permutations(folder_numbers, 2))
print(permutations)

# pretty print
for x, y in permutations:
    print(x, y)

Expected output

[('SUB00879', 'REZ00682'), ('SUB00879', 'DVP00464'), ('REZ00682', 'SUB00879'), ('REZ00682', 'DVP00464'), ('DVP00464', 'SUB00879'), ('DVP00464', 'REZ00682')]
SUB00879 REZ00682
SUB00879 DVP00464
REZ00682 SUB00879
REZ00682 DVP00464
DVP00464 SUB00879
DVP00464 REZ00682
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