python - 在列表 Python 中生成所有可能的二进制值组合
问题描述
我正在寻找一种在列表中生成所有可能的二进制组合的方法。例如,如果我有 5 个可用空间,我想创建一个列表,其中包含 ["00000", ..., "11111"] 中的所有可能组合,我不知道我是否解释得很好,我在这里发现了一些类似的问题,但我设法实现了它,因为我正在寻找......
indexNames = ["00000", "00001", "00010", ..., "11111"]
如果 n = 5。
indexNames = ["00", "01", "10", "11"]
如果 n = 2。
解决方案
您应该使用itertools.product
大致相当于生成器表达式中的嵌套 for 循环。例如, product(A, B)
返回与 ((x,y) for x in A for y in B)
嵌套循环像里程表一样循环,每次迭代时最右边的元素都会前进。此模式创建一个字典顺序,以便如果输入的可迭代对象已排序,则产品元组将按排序顺序发出。
from itertools import product
def get_binary(length):
perm=product(['0', '1'], repeat=length)
possible_bin=[]
for i in list(perm):
my_bin=''.join(i)
possible_bin.append(my_bin)
return possible_bin
print(get_binary(3))
print(get_binary(4))
print(get_binary(5))
['000', '001', '010', '011', '100', '101', '110', '111']
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', '10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111', '11000', '11001', '11010', '11011', '11100', '11101', '11110', '11111']
推荐阅读
- git - 无法推送到 GitHub 上的存储库
- python - 如何在 MacOS 上下载 discord.py?
- javascript - 如何使用谷歌 api 标记自定义在 WordPress 中将数据从 PHP 传递到 JS
- java - GUI 元素不会立即显示
- elasticsearch - 用无痛脚本语言在 Char 处拆分字符串
- python - 使用 beautifulsoup 抓取 aria-label 的数据
- json - JSON 数组中 JSON 值的 SUM 查询
- javascript - 将代码模块化会影响 react-app 的性能吗?
- .net-core - 在 .Net 5 中找不到 IActionSelectorDecisionTreeProvider 命名空间
- c++ - 在 MinGW 编译的 C++ 程序中播放音乐文件