Python:我如何使用itertools?

Kai*_*nen 6 python list python-itertools

我正在尝试制作一个包含所有可能的1和0变体的列表.例如,如果我只有两位数,我想要一个像这样的列表:

[[0,0], [0,1], [1,0], [1,1]]
Run Code Online (Sandbox Code Playgroud)

但如果我决定有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]]
Run Code Online (Sandbox Code Playgroud)

有人告诉我使用itertools,但我不能按照我想要的方式工作.

>>> list(itertools.permutations((range(2))))
[(0, 1), (1, 0)]
>>> [list(itertools.product((range(2))))]
[[(0,), (1,)]]
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?问题二,如何在这样的模块上找到文档?我只是在这里盲目地挥舞着

fal*_*tru 9

itertools.product(..,repeat = 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)]
Run Code Online (Sandbox Code Playgroud)

Python模块索引包含标准库模块文档的链接.


Ter*_*ryA 6

itertools.product()可以采取第二个论点:长度.正如您所见,它默认为1.简单地说,您可以添加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)]
Run Code Online (Sandbox Code Playgroud)

要查找文档,您可以使用help(itertools)或只是快速谷歌(或任何您的搜索引擎)搜索"itertools python".


Ste*_*nes 6

如何在itertools上找到一些信息(除了这里或google),或者几乎任何关于python的信息:

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  --
Run Code Online (Sandbox Code Playgroud)