0

I am trying to sort numerical tuples by two arguments:

  • first argument, lenght of the tuple: the smaller the tuple, the better;
  • second argument, the n-th value of the tuple: if two tuples have the same lenght, then they should be ordered by the first numerical value by which they differ

For example, let's say we have these four tuples:

    a = (2, 5)           # len(a) == 2
    b = (2, 5, 3)        # len(b) == 3
    c = (2, 4, 3)        # len(c) == 3
    d = (1, 4, 4, 8)     # len(d) == 4

The result I'm willing to obtain is a function that will help me sort these tuples so that:

  • a is the first tuple (the smallest one)
  • b and c follows (the middle ones)
  • d is the last tuple (the longest one)
  • since b and c both get the same lenght, they shall be ordered so that c comes before b, because while their first value is the same, c's second values is smaller than b's

Therefore, the four tuples above should be listed as [a, c, b, d].

Question is: how do I do it, knowing that the tuples have no fixed length, and they might differ at any value from the first to the last one?

jpp
  • 159,742
  • 34
  • 281
  • 339
SlyK
  • 175
  • 2
  • 14

1 Answers1

3

You can sort tuples with... tuples:

res = sorted([a, b, c, d], key=lambda x: (len(x), x))

# [(2, 5), (2, 4, 3), (2, 5, 3), (1, 4, 4, 8)]

The key is the key argument, which utilises an anonymous (lambda) function. Python sorts tuples by element. So the first element len(x) gives priority to length of tuple. The second element x gives secondary importance to sorting by the tuple itself, which itself is performed element-wise.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Oh you fast, I was somewhere else, vn – vash_the_stampede Sep 24 '18 at 23:04
  • Alright, that works wonderfully! Thanks! Now, if I may ask again: what if I had to sort for a certain attribute of an object, instead of the numeric value? I mean, what if I had a = (Obj(id=2), Obj(id=5)), b = (Obj(id=2), Obj(id=5), Obj(id=3)), and so on, and I wanted them to be ordered as above? – SlyK Sep 24 '18 at 23:19
  • See [How to sort a list of objects based on an attribute of the objects?](https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) – jpp Sep 24 '18 at 23:21