python排列和组合

1.排列

1.1给定字符串,返回它的所有组合,如‘abc’, 返回‘abc’,‘acb’,‘bac,‘bca’,’cab‘,’cba‘
import itertools
s = 'abc'
itertools.permutations(s,len(s))    # 是迭代器
list(itertools.permutations(s,len(s)))   # list一下
结果如下:
    [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]  #只要拼接成字符串即可
    
[''.join(i) for i in list(itertools.permutations(s,len(s)))]:
    #结果 ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

2.补充知识

[''.join(i) for j in range(len(s)+1) for i in list(itertools.permutations(s,j))]
 # 有点像关联子查询的味道 
[i  for j in range(5) for i in range(j)]  
	# 先执行for j in range(5) 第一次 j = 0 把j给后面 就是 [i for i in range(0)] 为 空
    # 第二次 j = 1   [i for i in range(1)]   此时  [0]
    #第三次 j = 2   [i for i in range(2)]   此时  [0,1]
    #第二次 j = 3   [i for i in range(3)]   此时  [0,1,2]
    #第二次 j = 4   [i for i in range(4)]   此时  [0,1,2,3]
    结果就是
    [0,0,1,0,1,2,0,1,2,3]

3.组合

3.1获取所有组合abc,选两个,一共有 ab,ac bc 这是组合

import itertools
s = 'abc'
[i for i in list(itertools.combinations(s,2))]
[('a', 'b'), ('a', 'c'), ('b', 'c')]

4.combinations 和 permutations的区别

前者是组合,后者是排列(考虑先后顺序)
 
永远不要高估自己
原文地址:https://www.cnblogs.com/liqiangwei/p/14482743.html