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

Time:03-27

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:

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?

CodePudding user response:

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
  • Related