我想知道一种简单而Python的方法来获取所有长度为n的字符串,这些字符串由名为L列表中包含的字符组成。
例如:
L = ['0','1']
n = 3
如何获取:
['000','001','010','011','100','101','110','111']
一种可能的解决方案是使用CCD_ 1。它有效,但不是很优雅,所以我正在寻找一个更蟒蛇的解决方案。情况如下:
L = ['0','1']
n = 3
a = [L for i in range(n)]
x = list(itertools.product(*a))
x = ["".join(i) for i in x]
结果列表如下所示:
>>> x
['000', '001', '010', '011', '100', '101', '110', '111']
有没有像all_possible_strings(L, n)
这样的内置元素,它接受L中的元素,并获得长度n与这些元素的所有可能组合?
使用产品的重复选项似乎可以更直接地满足您的需求:
L = ['0','1']
n = 3
x = list(itertools.product(L, repeat=n))
x = ["".join(i) for i in x]
print(x)
输出:
['000', '001', '010', '011', '100', '101', '110', '111']
以下代码使用Python 2.6及以上版本ONLY
首先,导入itertools:
import itertools
排列(顺序问题(:
print list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
(2, 1), (2, 3), (2, 4),
(3, 1), (3, 2), (3, 4),
(4, 1), (4, 2), (4, 3)]
文档:
https://docs.python.org/2/library/itertools.html#itertools.permutations
快乐编码