Skip to main content
Question Protected by eyllanesc

I have a list of lists (which could have been tuples, but I digress) in a format such as:

[12[[12, 'tall', 'blue', 1]
[15, 'tall', 'black', 3]
[13, 'tall', 'blue', 8]
[9, 'short', 'blue', 3]
[1, 'short', 'black', 2]
[2, 'short', 'red', 9],
[4, 'tall', 'blue', 13]13]]

If I wanted to sort by one element, say the tall/short element, I could do it via s = sorted(s, key = itemgetter(1)).

If I wanted to sort by BOTHboth tall/short and colour, I could do the sort twice. Once, once for each element. However, thisbut is computationally ridiculous. Is there a quicker way?

I have a list of lists (which could have been tuples, but I digress) in a format such as:

[12, 'tall', 'blue', 1]
[15, 'tall', 'black', 3]
[13, 'tall', 'blue', 8]
[9, 'short', 'blue', 3]
[1, 'short', 'black', 2]
[2, 'short', 'red', 9]
[4, 'tall', 'blue', 13]

If I wanted to sort by one element, say the tall/short element, I could do it via s = sorted(s, key = itemgetter(1))

If I wanted to sort by BOTH tall/short and colour, I could do the sort twice. Once for each element. However, this is computationally ridiculous. Is there a quicker way?

I have a list of lists:

[[12, 'tall', 'blue', 1],
[2, 'short', 'red', 9],
[4, 'tall', 'blue', 13]]

If I wanted to sort by one element, say the tall/short element, I could do it via s = sorted(s, key = itemgetter(1)).

If I wanted to sort by both tall/short and colour, I could do the sort twice, once for each element, but is there a quicker way?

Source Link
headache
  • 8.7k
  • 5
  • 19
  • 6

Sort a list by multiple attributes?

I have a list of lists (which could have been tuples, but I digress) in a format such as:

[12, 'tall', 'blue', 1]
[15, 'tall', 'black', 3]
[13, 'tall', 'blue', 8]
[9, 'short', 'blue', 3]
[1, 'short', 'black', 2]
[2, 'short', 'red', 9]
[4, 'tall', 'blue', 13]

If I wanted to sort by one element, say the tall/short element, I could do it via s = sorted(s, key = itemgetter(1))

If I wanted to sort by BOTH tall/short and colour, I could do the sort twice. Once for each element. However, this is computationally ridiculous. Is there a quicker way?