python长度为0.1的所有可能的组合 [英] python all possible combinations of 0,1 of length k

查看:84
本文介绍了python长度为0.1的所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要长度k的0,1的所有可能组合。

I need all possible combinations of 0,1 of length k.

假设k = 2我想要(0,0),( 0,1),(1,0),(1,1)

Suppose k=2 I want (0,0), (0,1), (1,0), (1,1)

我在中尝试了其他功能itertools ,但我没有找到想要的东西。

I have tried different function in itertools but I did not find what I want.

>>> list(itertools.combinations_with_replacement([0,1], 2))
[(0, 0), (0, 1), (1, 1)]
>>> list(itertools.product([0,1], [0,1])) #does not work if k>2
[(0, 0), (0, 1), (1, 0), (1, 1)]


推荐答案

itertools.product() 需要 repeat 关键字参数;将其设置为 k

itertools.product() takes a repeat keyword argument; set it to k:

product(range(2), repeat=k)

演示:

>>> from itertools import product
>>> for k in range(2, 5):
...     print list(product(range(2), repeat=k))
... 
[(0, 0), (0, 1), (1, 0), (1, 1)]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
[(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), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]

这篇关于python长度为0.1的所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆