0

I have a questions about python sorting functions. I cannot digest how it works actually. Here is my class:

class DataScript(object):

    def __init__(self, index, name, size):
        self.index = index
        self.name = name
        self.size = size

    def __cmp__(self, other):
        if hasattr(other, 'getKey'):
            if self.getKey() == other.getKey():
                return 0
            else:
                if self.getKey() > other.getKey():
                    return 1
                else:
                    return -1

    def getKey(self):
        return self.size

    def __iter__(self):
        return self

    def __next__(self):
        self.index += 1
        try:
            return data[self.index - 1]
        except IndexError:
            self.idx = 0
            raise StopIteration  # Done iterating.

    def __repr__(self):
        return '[' + str(data.index) + ', ' + data.name + ', ' + convert_bytes(data.size) + ']'

It is said that I have to give the list which I want to sort and the getKet function to get the sorting key. However when I try to run such a thing like this: I get an error that something is not iterable or there is no getKey function for the object in question ? Here is how I call it and I have to say it has no sense for me. First example doesn't work and I'm guessing it cannot actually determine item index and doing nothing. Second example works and I don't understand why.

sorted(resultList, key=resultList.getKey)

or

resultList.sort(key=resultList.getKey)
smoczyna
  • 489
  • 6
  • 18
  • 1
    "doesn't work" is not a problem specification. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Aug 15 '18 at 16:31
  • 1
    Note that `sorted` *returns* a sorted list, without altering the original. The command you gave simply discards the result, unless it's run from the Python shell (which would print the return value). – Prune Aug 15 '18 at 16:32
  • It will probably be very easy to fix your problem **IF** you follow @Prune's advice and provide a complete example that doesn't rely on missing variables and functions (`resultList`, `data`, and `convert_bytes`), and you show us exactly what you tried and the exact error message you saw. (For example, one error message probably resulted from using `resultList.getKey` when `resultList` was a list; another probably resulted from a different `resultList` that was a `DataScript` object. Providing a consistent example will help us help you.) – K. A. Buhr Aug 15 '18 at 16:38
  • you see, you are right (in your second comment Prune) I missed that fact thus "sorted" function seemed not to work. By not working I meant it does not sort anything but it actually does. Thanks – smoczyna Aug 16 '18 at 16:06

2 Answers2

1

One way of sorting a list of DataScript would be:

sorted(resultList, key=lambda elem: elem.getKey())

For more infos see here

SimpleNotGood
  • 345
  • 3
  • 14
1

Why not:

from operator import attrgetter

sorted(resultList, key=attrgetter('size'))
PMende
  • 5,171
  • 2
  • 19
  • 26