2013-02-16 60 views
0

假设我有一个字节列表(x00 to xFF)。如何使用itertools只返回有十 因此,例如,我想与长度为3的所有排列的长度排列,然后我会得到如何使用itertools输出只有一定长度的结果

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

这样,没有计算资源的浪费。

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

回答

3
import itertools 
for tup in itertools.product(range(0x100), repeat=3): 
    ... 
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的答案中一样。

+0

不知道这是否是OP想要的。您没有[x00,x01,x00],[x01,x00,x00]等这种方式 – 2013-02-16 22:56:16

+0

@gnibbler。是的,现在我找到了你。由于没有在OP的输出中特别指定,所以我首先弄错了。 :) – 2013-02-16 23:04:31

+0

是的,我想重复,就像@gnibbler陈述 – drum 2013-02-16 23:14:09

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)]