-2

I have the following code:

lst = []

class DATA:
    def __init__(self):
        s = ['','']

def fillLst():
    d1 = DATA()
    d1.s[0] = 'zebra'
    d1.s[1] = 23

    d2 = DATA()
    d2.s[0] = 'airplane'
    d2.s[1] = 435

    d1 = DATA()
    d1.s[0] = 'aira'
    d1.s[1] = 211


    lst.append(d1)
    lst.append(d2)
    lst.append(d3)

When I print the list I get the following:

zebra - 23
aira - 211
airplane - 435

Now I want to sort the list so that I get this output:

aira - 211
airplane - 435
zebra - 23

So how can I sort the list with the Data objects in it?

martineau
  • 119,623
  • 25
  • 170
  • 301
Markus
  • 5
  • 1
  • 2
    What have you tried to tackle this so far? There's many good questions here and also a really good official [howto on sorting](https://docs.python.org/3/howto/sorting.html). – Dimitris Fasarakis Hilliard Apr 14 '17 at 17:37
  • Possible duplicate of [How to sort (list/tuple) of lists/tuples?](http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – vallentin Apr 14 '17 at 17:40
  • The code you posted is full of typos (missing `self`, `d1` instead of `d3`...) and can't even be executed. Please paste the *exact* code that caused you a problem! – Thierry Lathuille Apr 14 '17 at 17:45

1 Answers1

3

You could do this:

sorted(lst, key=lambda data: data.s[0])

If you want to sort elements in lst by s[0].

sorted function has a parameter key that you can specify a function that returns the key to sort.

sorted function in Python Document:

sorted(iterable[, key][, reverse])

...

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

Community
  • 1
  • 1
Laurence
  • 721
  • 7
  • 24