0

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

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

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

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

4

3 回答 3

3
import itertools
for tup in itertools.product(range(0x100), repeat=3):
    ...
于 2013-02-16T22:50:25.317 回答
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 的回答。

于 2013-02-16T22:48:14.390 回答
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)]
于 2013-02-16T22:58:03.270 回答