1

I have this class called Suffix():

class Suffix:
    def __init__(self, index, suffix):
        self.index = index #int
        self.suffix = suffix #string
    
    def __repr__(self):
        return f'({self.index},{self.suffix})'

I have a list with a bunch of instances from this class called sa = [suffix list]

Now I want to sort sa alphabetically according to the first 36 characters of the suffix string of the suffix.

I found Sort strings by the first N characters that showed me

sorted(array, key=lambda x:x[:24])

But is there a way to implement this without putting all my suffixes into a seperate array, that would defeat my purpose.

nibs
  • 63
  • 6
  • 3
    That would be something like `key=lambda x: x.suffix[:36]`. – jasonharper May 03 '21 at 16:02
  • it still gives me the error of 'list' object has no attribute 'suffix'. This is the code: sa_array = np.asarray(sa) sa_array_flat = sa_array.flatten() #flattened by default in row-major ("C"-style) sa_sorted = sorted(sa_array_flat, key=lambda x: x.suffix[:36]) I flattened the array because I figures it might be that, but no luck – nibs May 04 '21 at 09:24
  • You have somehow ended up with an array of lists, rather than an array of `Suffix` instances. I'm not sure why numpy is involved here at all, that's primarily useful with numeric arrays. – jasonharper May 04 '21 at 12:49

1 Answers1

1

If you define __lt__, __gt__, __eq__, __le__, __ge__, __ne__ to use the first 36 characters you can use the built is sort function of python on your custom

Tamir
  • 965
  • 4
  • 17