我们可以假设像 [14,983,2567] 这样的一个列表是一个数字序列 149832567,然后我们添加两个逗号,一个在 4 之后,另一个在 3 之后,因此我们生成了三个数字 [14,983,2567] .
那么,可以生成多少个数列呢?
In [1]: import itertools
In [2]: a = range(1,10)
In [3]: a
Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [4]: len(list(itertools.permutations(a,9)))
Out[4]: 362880
当我们得到一个像437865192这样的数列时,可以生成多少个三元数?组合
8*7/2 = 28(在 9 个数字之间选两个空格)
或使用itertools.combinations
In [8]: len(list(itertools.combinations(list(range(8)),2)))
Out[8]: 28
给定一个序列,我们将得到 28 种组合。
In [1]: a = ['2','3','6','4','9','1','7','8','5']
In [2]: import itertools
In [4]: for i in itertools.combinations(range(1,9),2):
...: print [int(''.join(a[:i[0]])), int(''.join(a[i[0]:i[1]])), int(''.join(a[i[1]:]))]
[2, 3, 6491785]
[2, 36, 491785]
[2, 364, 91785]
[2, 3649, 1785]
[2, 36491, 785]
[2, 364917, 85]
[2, 3649178, 5]
[23, 6, 491785]
[23, 64, 91785]
[23, 649, 1785]
[23, 6491, 785]
[23, 64917, 85]
[23, 649178, 5]
[236, 4, 91785]
[236, 49, 1785]
[236, 491, 785]
[236, 4917, 85]
[236, 49178, 5]
[2364, 9, 1785]
[2364, 91, 785]
[2364, 917, 85]
[2364, 9178, 5]
[23649, 1, 785]
[23649, 17, 85]
[23649, 178, 5]
[236491, 7, 85]
[236491, 78, 5]
[2364917, 8, 5]
因此将生成 10160640(362880*28) 个列表。
最终代码:
In [15]: a=map(lambda x:str(x), range(1,10))
In [16]: a
Out[16]: ['1', '2', '3', '4', '5', '6', '7', '8', '9']
In [17]: result = []
In [18]: for seq in itertools.permutations(a,9):
...: for i in itertools.combinations(range(1,9),2):
...: result.append([int(''.join(seq[:i[0]])), int(''.join(seq[i[0]:i[1]])), int(''.join(seq[i[1]:]))])
...:
In [19]: len(result)
Out[19]: 10160640