-1

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

sacuL
  • 49,704
  • 8
  • 81
  • 106

4 Answers4

3

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']
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • just like the above answer, the result of your code is string binary digits : ['0001', '0010', '0011', '0100', '0101'] but how can I obtain integer as result like : [0001, 0010, 0011, 0100, 0101] – Abolfazl ghiasi Oct 29 '18 at 22:24
  • 1
    You can't, those aren't integers if they're zero padded. – sacuL Oct 29 '18 at 22:25
2

Another hacky way to achieve this is:

listres = [str(bin(x))[2:].zfill(4) for x in lista]
pawloka
  • 118
  • 6
  • the result of your code is string binary digits : ['0001', '0010', '0011', '0100', '0101'] but how can I obtain integer as result like : [0001, 0010, 0011, 0100, 0101] – Abolfazl ghiasi Oct 29 '18 at 22:19
0

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

Michael
  • 2,344
  • 6
  • 12
-1

Use bin method;

>>> a = bin(6)
>>>a

'0b110'
a[2:]
110