Python:我该如何使用itertools?

5
我想制作一个包含1和0的所有可能性的列表。例如,如果我只有两个数字,我想要像这样的列表:
[[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,)]]

有办法可以做到这一点吗?另外第二个问题,我该如何找到关于这样的模块的文档?我在这里感觉很茫然。
3个回答

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

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


@Marcin:是的,它可以。 - Martijn Pieters

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

要查找文档,您可以使用help(itertools)或快速地在Google(或其他搜索引擎)上搜索“itertools python”。

6
如何查找itertools相关信息(除了这里或谷歌),或者任何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  --

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接