本文介绍了在python中生成两项的所有可能长度为n的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从两个可能的项目生成长度为n的列表。例如一个示例可能是长度为4的列表,包括零或一个将为0000、0001、0010、0100、1000、1001等。预先感谢, Jack
I am trying to generate a list of length n from two possible items. e.g. One example could be, a list of length 4 comprising zeros or ones which would be 0000, 0001, 0010, 0100, 1000, 1001, etc. Thanks in advance, Jack
推荐答案使用 itertools.product :
In [1]: from itertools import product In [2]: list(product((0, 1), repeat=4)) Out[2]: [(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)]以整数字符串形式打印int:
You can also just print ints as binary strings:
In [3]: for i in range(2**4): ...: print('{:04b}'.format(i)) ...: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111更多推荐
在python中生成两项的所有可能长度为n的组合
发布评论