Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

python - How to get all combination of n binary value?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use itertools.product

import itertools
lst = list(itertools.product([0, 1], repeat=3))

This will yield a list of tuples (see here)

You can easily change this to use a variable repeat:

n = 3
lst = list(itertools.product([0, 1], repeat=n))

If you need a list of lists, then you can use the map function (thanks @Aesthete).

lst = map(list, itertools.product([0, 1], repeat=n))

Or in Python 3:

lst = list(map(list, itertools.product([0, 1], repeat=n)))
# OR
lst = [list(i) for i in itertools.product([0, 1], repeat=n)]

Note that using map or a list comprehension means you don't need to convert the product into a list, as it will iterate through the itertools.product object and produce a list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...