简体   繁体   中英

Generating 2-d array of binary numbers in python

So this is what im trying in Python.`

input = []
for i in range(10):
  n = getBin(i, 4)
  input.append(n)
print input

It is giving as:

['0000', '0001', '0010', '0011', '0100', 
 '0101', '0110', '0111', '1000', '1001']

And what I need is as:

[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1], [0, 1, 0, 0],
 [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1]]

Using itertools.product with (0, 1) and 4 repeats:

input = [list(x) for x in itertools.product((0, 1), repeat=4)]

If you're ok with a list of tuple s rather than of list s, you can simply do:

input = list(itertools.product((0, 1), repeat=4))

Or simplest of all, if you will be iterating over it anyway, there's no need to make it a list :

input = itertools.product((0, 1), repeat=4)

Lastly, (0, 1) could be range(2) , but that's hardly an improvement


itertools.product generally tries to return in the same format you gave it. So by feeding a string, it returns a string. Feed it a list and it...almost returns a list (returns a tuple)

Your getBin returns a binary number in string format, we convert each and every character to an integer with int and return a list.

result = [map(int, getBin(i,4)) for i in range(10)]

For example,

def getBin(number, total):
    return bin(number)[2:].zfill(total)

result = [map(int, getBin(i, 4)) for i in range(10)]

print result

Output

[[0, 0, 0, 0],
 [0, 0, 0, 1],
 [0, 0, 1, 0],
 [0, 0, 1, 1],
 [0, 1, 0, 0],
 [0, 1, 0, 1],
 [0, 1, 1, 0],
 [0, 1, 1, 1],
 [1, 0, 0, 0],
 [1, 0, 0, 1]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM