Reputation: 1281
I have the following list in Python which comprises 0s.
lst = [0,0,0,0,0]
I’d like to create a list which comprises of lists of different combinations of 1s and 0s. Each list would be a new and unique combination and together all the possible combinations can be found in it. It would look a bit like this, if it was only with 3 items:
lst = [[0,0,0], [0,0,1], [0,1,0], [1,0,0], [0,1,1], [1,1,0], [1,0,1], [1,1,1]]
Thanks!
Upvotes: 0
Views: 122
Reputation: 76
Three bit combinations without importing packages:
lst = []
z = [lst.append(list(format(i,'03b'))) for i in range(0,2**3)]
lst
[['0', '0', '0'], ['0', '0', '1'], ['0', '1', '0'], ['0', '1', '1'], ['1', '0', '0'], ['1', '0', '1'], ['1', '1', '0'], ['1', '1', '1']]
For 4 bits wide, change '03b' to '04b' and range to (0,2**4)
Upvotes: 0
Reputation: 1115
You can use the itertools
package, it contains the product
function
from itertools import product
list(product([0,1],repeat=5))
see https://docs.python.org/3/library/itertools.html#itertools.product
edit: note that the right use of some functions from this package could give you your expected output without making for loops. As others said, it's hard to know what you want exactly.
Upvotes: 1
Reputation: 2025
I am not sure what you want, but the following looks like your need.
import numpy as np
lst = [0,0,0,0,0]
tmp = []
for i in range(len(lst)):
l = np.copy(lst)
l[i] = 1
tmp.append(l.tolist())
print(tmp)
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]
Upvotes: 0