I have an object roughly like so:
class Hand(object):
def __init__(self, finger_names, finger_lengths, nail_sizes):
self.finger_names = finger_names
self.finger_lengths = finger_lengths
self.nail_sizes = nail_sizes
def _sort_by_finger_lengths(self):
????
finger_names, finger_lengths and nail_sizes are all either equally long lists or empty (for example, if the person hasn’t measured their nail_sizes yet). The goal is to sort the attributes of the object by finger_lengths. So if you start with a Hand object where the lists are ordered by left-to-right names (pinky, ring, middle, pointer, thumb), you end up with a Hand object with all attributes sorted by finger_lengths.
Like so:
finger_names = [pinky, thumb, pointer, ring, middle]
finger_lengths = [6, 7, 12, 13, 15]
nail_sizes = []
EDITED TO ADD: Hand is just an example class. The real code has good reasons for having lists for each attribute.
One simple approach is to do this:
However, Nick is right that you should probably link these up in a data structure, instead of depending on their order to associate them.
The above strategy (using
key) still works in that case, but you don’t need to usezip(*s_tuples)to disassociate them.On the other hand, if you want to disassociate them, there’s a one-liner solution that I forgot about before.
Or, if you want to sort in place, saving one copy operation: