RythonDev
RythonDev

Reputation: 442

How to sort a list of binary strings

let's say for example I have a list of binary codes such as this:

a=['100','10','01010','000','0001','10001']

I want the sorted list to be:

a=['000','0001','10','100','01010','10001']

Upvotes: 2

Views: 1694

Answers (2)

SRG
SRG

Reputation: 345

a=['100','10','01010','000','0001','10001']
list=[bin(int(ele)) for ele in a]
list=[int(ele,0) for ele in list]

print(sorted(list))

output

[0, 1, 10, 100, 1010, 10001]

Upvotes: 0

Mykola Zotko
Mykola Zotko

Reputation: 17882

You can use the function int as a key:

sorted(a, key=lambda x: int(x, 2))
# ['000', '0001', '10', '100', '01010', '10001']

Upvotes: 5

Related Questions