python中,itertools模块中combinations和product的使用

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

官方文档

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

def combinations(iterable, r):

    # combinations('ABCD', 2) --> AB AC AD BC BD CD

    # combinations(range(4), 3) --> 012 013 023 123

    pool = tuple(iterable)

    = len(pool)

    if r > n:

        return

    indices = range(r)

    yield tuple(pool[i] for in indices)

    while True:

        for in reversed(range(r)):

            if indices[i] != + - r:

                break

        else:

            return

        indices[i] += 1

        for in range(i+1, r):

            indices[j] = indices[j-1+ 1

        yield tuple(pool[i] for 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)]

复制代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值