Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort numbers in one line

We have numbers in a string like this:

numbers = "1534423543"

We want to sort this and return:

"1,2,3,4,5" 

(only unique numbers!)

How to do it in ONE line?

like image 538
David Silva Avatar asked Oct 22 '12 17:10

David Silva


2 Answers

use set() to get unique items, then sort them using sorted() and finally join them using ",".join()

In [109]: strs="1534423543"

In [110]: ",".join(sorted(set(strs)))
Out[110]: '1,2,3,4,5'
like image 81
Ashwini Chaudhary Avatar answered Oct 19 '22 14:10

Ashwini Chaudhary


Ashwini has the answer that's on the tip of everyone's fingers - if you're up for an import, you could do...

from itertools import groupby; ','.join(k for k, g in groupby(sorted(nums)))

And that's almost one line :)

like image 22
Jon Clements Avatar answered Oct 19 '22 13:10

Jon Clements