Home > Software engineering >  Sort 2 lists of lists according to the following common rule
Sort 2 lists of lists according to the following common rule

Time:05-27

Given two lists, each of which contains lists, I want to sort both the lists according to the following common rule.

In the first list, if the lengths of the lists are not the same, sort them according to length first. Then, if two or more elements have the same lengths, sort them according to the usual sorting rule (lexicographic order).

Finally, assuming that the two lists are in one-one correspondence, sort the second list with the same permutation that was inherently used for the first.

For example, consider A = [[4,8],[8,9],[5]] and B = [[2,4],[1,3],[1,2]].

The first list, after sorting would be [[5],[4,8],[8,9]]. Due to this, the second should be [[1,2],[2,4],[1,3]].

I had a look at similar questions that were put up previously and the solution in most cases was using the zip function. But that does not work here because I am having to use two different sorting rules one after another.

CodePudding user response:

Try:

A = [[4, 8], [8, 9], [5]]
B = [[2, 4], [1, 3], [1, 2]]

idxs, A = zip(*sorted(enumerate(A), key=lambda k: (len(k[1]), k[1])))
B = [B[i] for i in idxs]

print(list(A))
print(B)

Prints:

[[5], [4, 8], [8, 9]]
[[1, 2], [2, 4], [1, 3]]
  • Related