Reputation: 21
I'm trying to sort a list of given type on the basis of the date
data = [('Anil Kumar', '18-08-2001'), ('Ajay Shastri', '18-08-2000'), ('Sumita Singh', '12-11-1885'), ('Rajni Patel', '11-01-1886'), ('Arshad Khan', '12-11-1887'), ('Christopher Diaz', '19-11-2005'), ('Abha Reddy', '01-01-2005')]
For that I am using map
and lambda
function
for k in range(len(data)):
finaldata = list(sorted(data[k][1], key=lambda d: map(int, d.split('-'))))
But I am getting this error
TypeError: '<' not supported between instances of 'map' and 'map'
Upvotes: 0
Views: 58
Reputation: 51643
Converting dates to datetimes would be the preferred way to do this, but you can also use number sorting or lexicographical sorting:
data = [('Anil Kumar', '18-08-2001'), ('Ajay Shastri', '18-08-2000'),
('Sumita Singh', '12-11-1885'), ('Rajni Patel', '11-01-1886'),
('Arshad Khan', '12-11-1887'), ('Christopher Diaz', '19-11-2005'),
('Abha Reddy', '01-01-2005')]
# integer sorting
finaldata = sorted(data, key=lambda d: list(reversed(list(map(int, d[1].split('-'))))))
# lexicograph sorting
finaldata = sorted(data, key=lambda d: list(reversed(d[1].split('-'))))
print(finaldata)
to get:
[('Sumita Singh', '12-11-1885'), ('Rajni Patel', '11-01-1886'),
('Arshad Khan', '12-11-1887'), ('Ajay Shastri', '18-08-2000'),
('Anil Kumar', '18-08-2001'), ('Abha Reddy', '01-01-2005'),
('Christopher Diaz', '19-11-2005')]
To additionall sort by the name you need to sort with a key of (date,name)
,
you can do this using:
finaldata = sorted(data,
key = lambda d: (list(reversed(list(map(int, d[1].split('-'))))),
d[0]))
Upvotes: 1
Reputation: 26315
Since map()
returns an iterator, you cannot use it like that in a comparison function, since you cannot do equality comparisons with two map
objects. Even if you cast to a list
or another collection, there are still many other problems with your code, as highlighted in @Patrick Artner's comment.
Instead you should use datetime.datetime.strptime
to convert the date strings to datetime objects for the comparison key
function.
The time format "%d-%m-%Y"
is good enough here, where %d
is zero padded days, %m
is zero padded months, and %Y
is years with century numbers included. You can refer to the strftime() and strptime() Format Codes from the documentation for further reading.
Demo
from datetime import datetime
data = [('Anil Kumar', '18-08-2001'), ('Ajay Shastri', '18-08-2000'), ('Sumita Singh', '12-11-1885'), ('Rajni Patel', '11-01-1886'), ('Arshad Khan', '12-11-1887'), ('Christopher Diaz', '19-11-2005'), ('Abha Reddy', '01-01-2005')]
print(sorted(data, key=lambda d: datetime.strptime(d[1], "%d-%m-%Y")))
Output:
[('Sumita Singh', '12-11-1885'), ('Rajni Patel', '11-01-1886'), ('Arshad Khan', '12-11-1887'), ('Ajay Shastri', '18-08-2000'), ('Anil Kumar', '18-08-2001'), ('Abha Reddy', '01-01-2005'), ('Christopher Diaz', '19-11-2005')]
Upvotes: 1