python - How to sort a list containing objects? -


i have 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 print list following:

zebra - 23 aira - 211 airplane - 435 

now want sort list output:

aira - 211 airplane - 435 zebra - 23 

so how can sort list data objects in it?

you this:

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

if want sort elements in lst s[0].

sorted function has parameter key can specify function returns key sort.

sorted function in python document:

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

...

key specifies function of 1 argument used extract comparison key each list element: key=str.lower. default value none (compare elements directly).


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -