0

I have a list with several registers from other lists. I put an index at the beginning of each element so that I can order it later, for writing purposes.

reg = index + ";" + cell[1] + ";" + hour + ";" + cell[0] + ";" + text[1] + ";"

At the end, reg should give something like this:

['5;01;11.32;RN_RT;Prep;', '9;02;2.12;ING;Prep;', '1;06;4.23;ING;Rec;']

Is there a way to order/sort it using the index at the beginning?

Mike Müller
  • 82,630
  • 20
  • 166
  • 161

2 Answers2

1

Sort with key=lambda s: int(s.split(';', 1)[0]).

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • I have never used lambda, can you explain a bit how it would work for the sorting? – Joshua Cazares Jan 20 '16 at 22:27
  • 1
    @JoshuaCazares If you've never used lambdas, [read the documentation](https://docs.python.org/2/tutorial/controlflow.html#lambda-expressions). – Peter Wood Jan 20 '16 at 22:30
  • See also [Why are Python lambdas useful?](http://stackoverflow.com/questions/890128/why-are-python-lambdas-useful) – Peter Wood Jan 20 '16 at 22:32
1

You can write a small helper function:

def by_index(x):
    return int(x.split(';', 1)[0])

and use it for sorting:

L = ['5;01;11.32;RN_RT;Prep;','9;02;2.12;ING;Prep;','1;06;4.23;ING;Rec;']

sorted(L, key=by_index)

['1;06;4.23;ING;Rec;', '5;01;11.32;RN_RT;Prep;', '9;02;2.12;ING;Prep;']

The function sorted() takes the keyword argument key:

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).

This function is called for each element in the list. So:

int(x.split(';', 1)[0])

splits off the value before the first ; and turns it into an integer. This is the index. This index will be used for sorting (the sorting key) but the sort result is the list elements in the order of the index.

lambda is just another way to define a function without using def. It is limited to expressions but can be used inline.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161