How to sort a list of binary strings

坚强是说给别人听的谎言 提交于 2021-02-16 15:17:12

问题


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']

回答1:


You can use the function int as a key:

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



回答2:


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]


来源:https://stackoverflow.com/questions/59006362/how-to-sort-a-list-of-binary-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!