python - lambda sorted list strange behavior -
when sort first , second element in list(tuple), works, sorting third element not working more input:
mylist=[('11', '82075.36', '8.15'), ('16', '82073.78', '12.92'), ('13', '62077.99', '17.89'),] the request:
print(sorted(mylist, key=lambda val: val[0])) print(sorted(mylist, key=lambda val: val[1])) print(sorted(mylist, key=lambda val: val[2])) and output:
[('11', '82075.36', '8.15'), ('13', '62077.99', '17.89'), ('16', '82073.78', '12.92')] # ok [('13', '62077.99', '17.89'), ('16', '82073.78', '12.92'), ('11', '82075.36', '8.15')] # ok` [('16', '82073.78', '12.92'), ('13', '62077.99', '17.89'), ('11', '82075.36', '8.15')] # seems not correct, can explain why? if remove quotes third elm works, anyhow, elm 1 works without removing quotes
mylist=[('11', '82075.36', 8.15), ('16', '82073.78', 12.92), ('13', '62077.99', 17.89),] and output:
[('11', '82075.36', 8.15), ('16', '82073.78', 12.92), ('13', '62077.99', 17.89)]
you're asking strings sorted, you're getting string sorting. try instead:
print(sorted(mylist, key=lambda val: int(val[0]))) print(sorted(mylist, key=lambda val: float(val[1]))) print(sorted(mylist, key=lambda val: float(val[2]))) i.e. change sort keys numerics.
Comments
Post a Comment