开发者

Generate Binary Table with Itertools

开发者 https://www.devze.com 2023-02-15 16:11 出处:网络
So this is what im trying list(itertools.combinations_with_replacement(\'01\', 2)) but this is开发者_StackOverflow社区 generating [(\'0\', \'0\'), (\'0\', \'1\'), (\'1\', \'1\')]

So this is what im trying

list(itertools.combinations_with_replacement('01', 2))

but this is开发者_StackOverflow社区 generating [('0', '0'), ('0', '1'), ('1', '1')]

I still need a ('1','0') tuple, is there a way to make itertools also do combinations and order?


Use

list(itertools.product(*["01"] * 2))

instead.


To take the cartesian product of a value with itself, you use

itertools.product("01", repeat=2)

This will give you all possible combinations.


To generalize for lists (instead of string) use:

list(itertools.product(*[[0,1]]*2))

This will give

[(0, 0), (0, 1), (1, 0), (1, 1)]


This program generates the numbers from 1 to 100 then converts it to binary

a=0
while a<100:
 a=a+1
 print a,"=",bin(a)
0

精彩评论

暂无评论...
验证码 换一张
取 消