Home > Software engineering >  How to sort itertools.combinations results by descending
How to sort itertools.combinations results by descending

Time:04-20

I have a list and want to find all possible combinations, I'm using below code

from itertools import combinations

cols=['AA','XY','GH','SD','DT']
col_comb =list()

for n in range(2,len(cols) 1):
    col_comb  = list(combinations(cols,n))

print (col_comb) 

I want to sort the output combination of above in descending order of number of elements, expected output like this,

[('AA', 'XY', 'GH', 'SD', 'DT'),('AA', 'XY', 'GH', 'SD'), ('AA', 'XY', 'GH', 'DT'), ('AA', 'XY', 'SD', 'DT'), ('AA', 'GH', 'SD', 'DT'), ('XY', 'GH', 'SD', 'DT'),('AA', 'XY', 'GH'), ('AA', 'XY', 'SD'), ('AA', 'XY', 'DT'), ('AA', 'GH', 'SD'), ('AA', 'GH', 'DT'), ('AA', 'SD', 'DT'), ('XY', 'GH', 'SD'), ('XY', 'GH', 'DT'), ('XY', 'SD', 'DT'), ('GH', 'SD', 'DT'),('AA', 'XY'), ('AA', 'GH'), ('AA', 'SD'), ('AA', 'DT'), ('XY', 'GH'), ('XY', 'SD'), ('XY', 'DT'), ('GH', 'SD'), ('GH', 'DT'), ('SD', 'DT')]

CodePudding user response:

Just reverse your range to make it start from the largest n:

for n in range(2,len(cols) 1)[::-1]:
# or
for n in reversed(range(2,len(cols) 1)):
# or
for n in range(len(cols), 1, -1):

All of the above are essentially identical, performance-wise, on Python 3, so choose the one that looks nicest to you.

Side-note: As cols increases, this will blow your memory; you really don't want to be writing code that holds all the results of multiple calls to combinations unless you're 100% sure the inputs will always be small. You can and should print the results as you generate them, never listifying a single combinations, rather than accumulating them all in a list and printing that.

CodePudding user response:

You need to add the sorted function with as key the length of the tuple

from itertools import combinations

cols=['AA','XY','GH','SD','DT']
col_comb =list()

for n in range(2,len(cols) 1):
    col_comb  = list(combinations(cols,n))


sorted(col_comb,key=lambda x:len(x))
print (col_comb)
 `
  • Related