I am a list
[['12', '2017/6/10'],
['-2', '2017/5/10'],
['12', '2017/2/10']]
I need to sorted by first element numerically, second on time (or use a given function say second letter of the string)
I am a list
[['12', '2017/6/10'],
['-2', '2017/5/10'],
['12', '2017/2/10']]
I need to sorted by first element numerically, second on time (or use a given function say second letter of the string)
Is this what you want ?
from operator import itemgetter
LIST=[['12', '2017/6/10'],
['-2', '2017/5/10'],
['12', '2017/2/10']]
sorted(LIST, key=itemgetter(0,1))
Out[127]: [['-2', '2017/5/10'], ['12', '2017/2/10'], ['12', '2017/6/10']]
EDIT1 sorry overlook the character to numeric
sorted(LIST, key=lambda x: (int(x[0]), x[1]))
from datetime import datetime
l = [['12', '2017/6/10'],
['-2', '2017/5/10'],
['12', '2017/2/10']]
l.sort(key=lambda x: (int(x[0]), datetime.strptime(x[1], "%Y/%m/%d")))
print(l)
Pls, take a look at "%Y/%m/%d"
to see if that match your date format. Is not clear if the month or the day come first given the examples your used.
Besides, int(x[0])
could be some modifications depending on how long is your numerical values.
Use this :
sorted(a, lambda x,y: x[0]<y[0] or x[0]==y[0] and x[1]<y[1])
if you want to do a special cmp function on the second key, you could define a custom cmp function , E.g.
def cmp(sa,sb):
return sa[3] < sb[3]
sorted(a, lambda x,y: x[0]<y[0] or x[0]==y[0] and cmp(x[1],y[1]))
I think the solution is using 'key' argument to define sorting key and 'cmp' argument to define function