itertools类

这里记录下itertools中常用的排列,组合,笛卡尔积等方法

  1. 排列 permutations
    >>> from itertools import permutations
	>>> t = permutations([1,2,3],2)
	>>> list(t)
	[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
	>>> t = permutations([1,2,3],3)
	>>> list(t)
	[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
  1. 组合 combinations
	>>> from itertools import combinations
	>>> t = combinations([1,2,3],2)#第一个参数是序列,第二个参数是放回几个元素的组合
	>>> list(t)
	[(1, 2), (1, 3), (2, 3)]

	>>> t = combinations([1,2,3],3)
	>>> list(t)
	[(1, 2, 3)]

	>>> t = combinations([1,2,3],1)
	>>> list(t)
	[(1,), (2,), (3,)]

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

	>>> t = combinations([1,2,3],-1)
	Traceback (most recent call last):
	  File "<stdin>", line 1, in <module>
	ValueError: r must be non-negative
  • 笛卡尔积 product
	>>> from itertools import product
	>>> t = product([1,2,3],[4,5])
	>>> list(t)
	[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]

	>>> t = product([1,2,3],(4,5))#传入元组
	>>> list(t)
	[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]

	>>> t = product('hello','world')#传入字符串
	>>> list(t)
	[('h', 'w'), ('h', 'o'), ('h', 'r'), ('h', 'l'), ('h', 'd'), ('e', 'w'), ('e', 'o'), ('e', 'r'), ('e', 'l'), ('e', 'd'), ('l', 'w'), ('l', 'o'), ('l', 'r'), ('l', 'l'), ('l', 'd'), ('l', 'w'), ('l', 'o'), ('l', 'r'), ('l', 'l'), ('l', 'd'), ('o', 'w'), ('o', 'o'), ('o', 'r'), ('o', 'l'), ('o', 'd')]

	>>> t = product([1,2,3],(4))#两个参数必须是可迭代的
	Traceback (most recent call last):
	  File "<stdin>", line 1, in <module>
	TypeError: 'int' object is not iterable

	>>> t = product([1,2,3],(4,))#此时就不会报错
	>>> list(t)
	[(1, 4), (2, 4), (3, 4)]

	>>> t = product([1,2,3],)#传入一个序列就是分开
	>>> list(t)
	[(1,), (2,), (3,)]
  • 累加 accumulate
	>>> from itertools import accumulate
	>>> t = accumulate(range(1))
	>>> list(t)
	[0]

	>>> t = accumulate(range(2))
	>>> list(t)
	[0, 1]

	>>> t = accumulate(range(3))
	>>> list(t)
	[0, 1, 3]

	>>> t = accumulate(range(4))
	>>> list(t)
	[0, 1, 3, 6]

	>>> t = accumulate(range(0))
	>>> list(t)
	[]
##返回值就是传入序列对应位置及前n个元素的和组成的新列表
##例如
##输入
##[1,2,3,4,5]
##返回
##[1,3,6,10,15]
  • 连接容器 chain
	>>> x = chain(range(3),range(4),range(5))
	>>> list(x)
	[0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值