David Silva
David Silva

Reputation: 2017

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?

Upvotes: 11

Views: 801

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251041

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'

Upvotes: 29

Jon Clements
Jon Clements

Reputation: 142206

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 :)

Upvotes: 5

Related Questions