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.