Python 进阶 —— itertools

itertools,顾名思义,用作迭代的工具,它不会直接返回一个序列,而是返回一个可迭代的对象,用于 for 循环迭代取出,或者 list comprehension。


这里写图片描述

1. permutations vs combinations

Akn=n!(nk)!Ckn=n!(nk)!k!

也即排列是组合的 k! ,当 k=2 时,排列是组合的 2 倍;

也即是数学(组合数学)上的排列组合,permutation 对顺序敏感({1, 2}, {2, 1} 是不同的排列),combination 对顺序不敏感({1, 2, 3}, {1, 3, 2}, … 都是相同的组合)。

  • (1)实现 C23=3 (组合 3 者之中的两个)

    >>> from itertools import combinations, permutations
    >>> seq = ['r', 'g', 'b']
    >>> for c in combinations(seq, 2):
            print(c)
    ('r', 'g')
    ('r', 'b')
    ('g', 'b')
  • (2)实现 A23=6 (排列三者之中的两个)

    >>> from itertools import combinations, permutations
    >>> seq = ['r', 'g', 'b']
    >>> for c in permutations(seq, 2):
            print(c)
    ('r', 'g')
    ('r', 'b')
    ('g', 'r')
    ('g', 'b')
    ('b', 'r')
    ('b', 'g')

注意,permutations 方法并不去除重复项:

>> list(permutations([1, 1, 2]))
[(1, 1, 2), (1, 2, 1), (1, 1, 2), (1, 2, 1), (2, 1, 1), (2, 1, 1)]
>> set(permutations([1, 1, 2]))
{(1, 1, 2), (1, 2, 1), (2, 1, 1)}

1,1,2 三个数字的排列数应当为: A33A22=3

2. chain

顾名思义,连接;

>> chain([1, 2], [3, 4])
<itertools.chain at 0x3ddf278>
>> list(chain([1, 2], [3, 4]))
[1, 2, 3, 4]

Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted;

chain 功能上更多地等价于 list 的 extend 操作,而不是 zip。

chain 基本上实现了:

for iter in xx:
    for i in iter:
        ...
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值