Home > database >  Sort a list of tuples by time
Sort a list of tuples by time

Time:01-23

I have a list like this:

[('100701260', '10:23:15'),
   ('100701260', '07:52:27'),
   ('100700853', '09:26:52')]

Is it possible to sort it by time like this:

[('100701260', '07:52:27'),
('100700853', '09:26:52'),
('100701260', '10:23:15')]

I know it is possible to sort by date when we have a list. But I am not sure about a list of tuples.

CodePudding user response:

Using itemgetter:

>>> t = [('100701260', '10:23:15'),
...      ('100701260', '07:52:27'),
...      ('100700853', '09:26:52')]
>>> from operator import itemgetter
>>> sorted(t, key=itemgetter(1))
[('100701260', '07:52:27'),
 ('100700853', '09:26:52'),
 ('100701260', '10:23:15')]

Strings in %H:%M:%S format will already sort chronologically by default, so there's no need to convert into time instances.

CodePudding user response:

You can use time.strptime() for that:

import time

t = [
    ('100701260', '10:23:15'),
    ('100701260', '07:52:27'),
    ('100700853', '09:26:52')
]

t.sort(key=lambda(x: time.strptime(x[1], '%H:%M:%S'))

The snippet above will leave t with:

[('100701260', '07:52:27'), ('100700853', '09:26:52'), ('100701260', '10:23:15')]

And constructing on top of @wim's answer, you can do it without any import:

t = [
    ('100701260', '10:23:15'),
    ('100701260', '07:52:27'),
    ('100700853', '09:26:52')
]

t.sort(key=lambda x: x[1])

CodePudding user response:

Since DateTime objects can be compared to one another, all that is left to do is ask the sorted function to order the results using them (in this case the second element of each tuple).

data = [
    ('100701260', '10:23:15'),
    ('100701260', '07:52:27'),
    ('100700853', '09:26:52')
]
result = sorted(data, key=lambda x: x[1])
  • Related