Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent leading zeros after mapping to integer using python

I want to sort a list numerically

s = [['92', '022'],['82','12'],['77','13']]

so I used,

s = [list( map(int,i) ) for i in s]     

s.sort()

and output came

[[77, 13],[82, 12],[92, 22]] 

But I want to keep that 22 as it is ie., "022" so, my question is how to prevent that leading zero!

like image 784
ssp4all Avatar asked May 13 '26 05:05

ssp4all


1 Answers

You can use sorted instead with the following key, that way you'll avoid transforming the actual values with a list comprehension:

sorted(l, key = lambda x: int(x[0]))
[['77', '13'], ['82', '12'], ['92', '022']]

You can also use operators.itemgetteras suggested by @aws_apprentice:

sorted(l, key = lambda x: int(itemgetter(0)(x)))
[['77', '13'], ['82', '12'], ['92', '022']]
like image 143
yatu Avatar answered May 14 '26 19:05

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!