How to generate combination of fix length strings using a set of characters?

六眼飞鱼酱① 提交于 2019-12-11 09:06:49

问题


In Python, how can I generate a string with all combinations of a set of characters up to a certain length?

I know how to use itertools to generate all combinations and permutations, but I can't figure out how to generate strings of dynamic length.

For example:

a = [0,1] length = 4

Result:

[0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1101, 1110, 1111]


回答1:


You could use itertools.product:

li = []
for i in itertools.product([0,1], repeat=4):
    li.append(''.join(map(str, i)))
print (li)

>>> li
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']

Possible one liner:

[''.join(map(str, i)) for i in itertools.product([0,1], repeat=4)]



回答2:


use product from itertools module.

>>> from itertools import product
>>> [i for i in product([0,1],repeat=4)]
[(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)]


来源:https://stackoverflow.com/questions/18772706/how-to-generate-combination-of-fix-length-strings-using-a-set-of-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!