如何使用itertools输出只有一定长度的结果

时间:2013-02-16 22:44:56

标签: python permutation itertools

假设我有一个字节列表(x00 to xFF)。如何使用itertools仅返回长度为X的排列。 所以例如我想要所有排列长度为3的排列,然后我会得到

[x00,x00,x00], [x00,x00,x01], ..., [xFF,xFF,xFF]

这样就不会浪费计算资源。

编辑:如果有更好的方法,不必是itertools。

3 个答案:

答案 0 :(得分:3)

import itertools
for tup in itertools.product(range(0x100), repeat=3):
    ...

答案 1 :(得分:1)

itertools.combinations_with_replacement

>>> my_list = [1, 2, 3, 4]
>>> import itertools
>>> 
>>> list(itertools.combinations_with_replacement(my_list, 3))
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), 
 (1, 2, 2), (1, 2, 3), (1, 2, 4), 
 (1, 3, 3), (1, 3, 4), 
 (1, 4, 4), 
 (2, 2, 2), (2, 2, 3), (2, 2, 4), 
 (2, 3, 3), (2, 3, 4), 
 (2, 4, 4), 
 (3, 3, 3), (3, 3, 4), 
 (3, 4, 4), 
 (4, 4, 4)]

好像你想要所有的排列,而不是替换。在这种情况下,您需要:itertools.product,如@ gnibbler的答案。

答案 2 :(得分:1)

看来@ gnibbler的解决方案更正确吗?

In [162]: >>> l = [1, 2, 3]

In [163]: list(itertools.combinations_with_replacement(l, 3))
Out[163]:
[(1, 1, 1),
 (1, 1, 2),
 (1, 1, 3),
 (1, 2, 2),
 (1, 2, 3),
 (1, 3, 3),
 (2, 2, 2),
 (2, 2, 3),
 (2, 3, 3),
 (3, 3, 3)]

In [164]: list(itertools.product(l, repeat=3))
Out[164]:
[(1, 1, 1),
 (1, 1, 2),
 (1, 1, 3),
 (1, 2, 1),
 (1, 2, 2),
 (1, 2, 3),
 (1, 3, 1),
 (1, 3, 2),
 (1, 3, 3),
 (2, 1, 1),
 (2, 1, 2),
 (2, 1, 3),
 (2, 2, 1),
 (2, 2, 2),
 (2, 2, 3),
 (2, 3, 1),
 (2, 3, 2),
 (2, 3, 3),
 (3, 1, 1),
 (3, 1, 2),
 (3, 1, 3),
 (3, 2, 1),
 (3, 2, 2),
 (3, 2, 3),
 (3, 3, 1),
 (3, 3, 2),
 (3, 3, 3)]