zoukankan      html  css  js  c++  java
  • Python:itertools模块 combinations和product的使用

    1.combinations(iterabler)  创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序:

    官方文档

    def combinations(iterable, r):
        # combinations('ABCD', 2) --> AB AC AD BC BD CD
        # combinations(range(4), 3) --> 012 013 023 123
        pool = tuple(iterable)
        n = len(pool)
        if r > n:
            return
        indices = range(r)
        yield tuple(pool[i] for i in indices)
        while True:
            for i in reversed(range(r)):
                if indices[i] != i + n - r:
                    break
            else:
                return
            indices[i] += 1
            for j in range(i+1, r):
                indices[j] = indices[j-1] + 1
            yield tuple(pool[i] for i in indices)
    

      

    def combinations(iterable, r):
        pool = tuple(iterable)
        n = len(pool)
        for indices in permutations(range(n), r):
            if sorted(indices) == list(indices):
                yield tuple(pool[i] for i in indices)

    例:

    >>> list(combinations(range(3),2))
    [(0, 1), (0, 2), (1, 2)]
    >>> list(combinations(range(3),3))
    [(0, 1, 2)]
    >>> list(combinations(range(3),1))
    [(0,), (1,), (2,)]

    2.product(*iterables[repeat])  创建一个迭代器,生成表示iterables中的项目的笛卡尔积的元组,repeat表示重复生成序列的次数。

    def product(*args, **kwds):
        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        pools = map(tuple, args) * kwds.get('repeat', 1)
        result = [[]]
        for pool in pools:
            result = [x+[y] for x in result for y in pool]
        for prod in result:
            yield tuple(prod)

     例:

    >>> list(product(range(3),repeat=1))
    [(0,), (1,), (2,)]
    >>> list(product(range(3),repeat=2))
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
    >>> list(product(range(3),repeat=3))
    [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]
  • 相关阅读:
    找出互联网符合的产品实例
    以软件周期来说明不同的测试的使用情况
    scrapy多个page爬取, post请求, 通过爬到的URL继续发请求爬页面
    Scrapy 安装, 基础使用, 持久化存储
    Linux nginx+uWSGI+django+virtualenv+supervisor发布web服务器
    Linux Nginx
    Linux virtualenv, virtualenvwrapper, pip freeze
    Linux Python安装
    Redis, Python操作Redis, Linux操作Redis, Redis命令, Redis发布订阅, Redis持久化, Redis主从同步
    爬虫 selenium
  • 原文地址:https://www.cnblogs.com/jeesezhang/p/3556232.html
Copyright © 2011-2022 走看看