Understanding lambda's sort function in python -
i trying sort list of lists in python. have written following code:
def sort(intervals): if intervals == [] : return [] intervals.sort(key = lambda x:x.start) return intervals = [[1,3],[8,10],[15,18],[2,6]] print(sort(a))
i getting following error:
attributeerror: 'list' object has no attribute 'start'
please can explain lambda function sort , details above error. thank you!!
the reason error message sort
ing based on attribute not list
(start
not attribute
of list')
, quick fix is, either use sort
method of list
or use built-in method sorted
:
1 - using sort
method of list
:
intervals.sort(key = lambda l:l[0])
2 - using built-in method sorted
:
intervals = sorted(intervals, key=lambda l:l[0])
reading more sorting list in wiki post, interesting.
Comments
Post a Comment