python itertools 组合_Python itertools 排列组合

组合

import itertools

nums = [1, 2, 3, 4, 5, 6, 7, 8]

for i in itertools.combinations(nums, 4):

print(i)

(1, 2, 3, 4)

(1, 2, 3, 5)

(1, 2, 3, 6)

(1, 2, 3, 7)

(1, 2, 3, 8)

。。。

(4, 5, 6, 8)

(4, 5, 7, 8)

(4, 6, 7, 8)

(5, 6, 7, 8)

排列

for i in itertools.permutations(nums, 4):

print(i)

(1, 2, 3, 4)

(1, 2, 3, 5)

(1, 2, 3, 6)

(1, 2, 3, 7)

。。。

(8, 7, 6, 2)

(8, 7, 6, 3)

(8, 7, 6, 4)

(8, 7, 6, 5)

product

从给定的序列中各取一个生成序列,可重复的排列数

product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)

product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...

for i in itertools.product([0, 1], repeat=3):

print(i)

(0, 0, 0)

(0, 0, 1)

(0, 1, 0)

(0, 1, 1)

(1, 0, 0)

(1, 0, 1)

(1, 1, 0)

(1, 1, 1)

combinations_with_replacement

combinations_with_replacement(iterable, r) --> combinations_with_replacement object

Return successive r-length combinations of elements in the iterable

allowing individual elements to have successive repeats.

combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC

可重复的组合数

for i in itertools.combinations_with_replacement([1, 2, 3, 4], 3):

print(i)

(1, 1, 1)

(1, 1, 2)

(1, 1, 3)

(1, 1, 4)

(1, 2, 2)

(1, 2, 3)

(1, 2, 4)

(1, 3, 3)

(1, 3, 4)

(1, 4, 4)

(2, 2, 2)

(2, 2, 3)

(2, 2, 4)

(2, 3, 3)

(2, 3, 4)

(2, 4, 4)

(3, 3, 3)

(3, 3, 4)

(3, 4, 4)

(4, 4, 4)

对比product

for i in itertools.product([1, 2, 3, 4], repeat=3):

print(i)

(1, 1, 1)

(1, 1, 2)

(1, 1, 3)

(1, 1, 4)

(1, 2, 1)

(1, 2, 2)

(1, 2, 3)

(1, 2, 4)

(1, 3, 1)

(1, 3, 2)

(1, 3, 3)

(1, 3, 4)

(1, 4, 1)

(1, 4, 2)

(1, 4, 3)

(1, 4, 4)

(2, 1, 1)

(2, 1, 2)

(2, 1, 3)

(2, 1, 4)

(2, 2, 1)

(2, 2, 2)

(2, 2, 3)

(2, 2, 4)

(2, 3, 1)

(2, 3, 2)

(2, 3, 3)

(2, 3, 4)

(2, 4, 1)

(2, 4, 2)

(2, 4, 3)

(2, 4, 4)

(3, 1, 1)

(3, 1, 2)

(3, 1, 3)

(3, 1, 4)

(3, 2, 1)

(3, 2, 2)

(3, 2, 3)

(3, 2, 4)

(3, 3, 1)

(3, 3, 2)

(3, 3, 3)

(3, 3, 4)

(3, 4, 1)

(3, 4, 2)

(3, 4, 3)

(3, 4, 4)

(4, 1, 1)

(4, 1, 2)

(4, 1, 3)

(4, 1, 4)

(4, 2, 1)

(4, 2, 2)

(4, 2, 3)

(4, 2, 4)

(4, 3, 1)

(4, 3, 2)

(4, 3, 3)

(4, 3, 4)

(4, 4, 1)

(4, 4, 2)

(4, 4, 3)

(4, 4, 4)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值