I have a list of decimal numbers as integers, and I want to convert them into binary. The output must be without 0b
prefix and also it must be 4 digits
like:
lista = [1,2,3,4,5,6,7,8,9,10]
listres = [0001,0010,0011,0100,...]
thanks in advance
I have a list of decimal numbers as integers, and I want to convert them into binary. The output must be without 0b
prefix and also it must be 4 digits
like:
lista = [1,2,3,4,5,6,7,8,9,10]
listres = [0001,0010,0011,0100,...]
thanks in advance
You can use map
with format
here, with '04b'
:
>>> list(map(lambda x: format(x,'04b'),lista))
['0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010']
Another hacky way to achieve this is:
listres = [str(bin(x))[2:].zfill(4) for x in lista]
This sounds like homework, so I'll just give a recommendation on how to proceed in creating the second list. If you know how to convert an integer into a binary representation, then you can use a list comprehension:
lista = [1,2,3,4,5,6,7,8,9,10]
listb = [integer_to_binary(n) for n in lista]
Here integer_to_binary() is just a function that converts an integer into its binary representation. It sounds like what you want is a string showing the binary representation, so I'll leave that to you to figure out (hint: try using format())