2013-07-18 32 views
4

我試圖讓含有1和所有可能的變化爲0。例如像列表,如果我剛纔兩位數字我希望像這樣的列表:Python:我如何使用itertools?

[[0,0], [0,1], [1,0], [1,1]] 

但是,如果我決定有3個數字我想擁有像這樣的列表:

[[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,1]] 

有人告訴我使用itertools,但我不能得到它的工作就是我想要的。

>>> list(itertools.permutations((range(2)))) 
[(0, 1), (1, 0)] 
>>> [list(itertools.product((range(2))))] 
[[(0,), (1,)]] 

有沒有辦法做到這一點?第二個問題,我如何找到像這樣的模塊的文檔?我只是一味地揮舞這裏

回答

5

itertools.product()可以採取第二個參數:長度。如你所見,它默認爲一個。簡單地說,你可以添加repeat=n到您的函數調用:

>>> list(itertools.product(range(2), repeat=3)) 
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] 

要查找的文檔,您可以使用help(itertools)或只是做一個快速谷歌(或其他搜索引擎)搜索「itertools蟒蛇」。

7

itertools.product(..,重複= N)

>>> import itertools 
>>> list(itertools.product((0,1), repeat=3)) 
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] 

Python Module Index包含標準庫模塊文檔鏈接。

+0

@Marcin:是的是的。 –

4

如何查找,或者是任何蟒蛇在itertools的一些信息,(比here或谷歌等):

python 
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] o 
win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import itertools 
>>> help(itertools) 
Help on built-in module itertools: 

NAME 
    itertools - Functional tools for creating and using iterators. 

FILE 
    (built-in) 

DESCRIPTION 
    Infinite iterators: 
    count([n]) --> n, n+1, n+2, ... 
    cycle(p) --> p0, p1, ... plast, p0, p1, ... 
    repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times 

    Iterators terminating on the shortest input sequence: 
    izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... 
    izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... 
    ifilter(pred, seq) --> elements of seq where pred(elem) is True 
    ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False 
    islice(seq, [start,] stop [, step]) --> elements from 
      seq[start:stop:step] 
    imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ... 
    starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ... 
    tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n 
-- More --