1. 程式人生 > >輕鬆用python實現排列組合功能

輕鬆用python實現排列組合功能

#! /usr/bin/env python

# -*- coding=utf-8 -*-

import itertools

list1 = 'abc'

list2 = []

for i in range(1,len(list1)+1):

   iter = itertools.combinations(list1,i)

   list2.append(list(iter))

print(list2)

列印後的結果:

[[('a',), ('b',), ('c',)], [('a', 'b'), ('a', 'c'),('b', 'c')], [('a', 'b', 'c')]]

2.排列

#! /usr/bin/env python

# -*- coding=utf-8 -*-

import itertools

list1 = 'abc'

list2 = []

for i in range(1,len(list1)+1):

   iter = itertools.permutations(list1,i)

   list2.append(list(iter))

print(list2)

打印出來的結果是:

[[('a',), ('b',), ('c',)], [('a', 'b'), ('a', 'c'),('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')], [('a', 'b', 'c'),('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'),('c', 'b', 'a')]]

以上只是簡單舉例,具體怎麼用,就看各位的靈活運用了,一通百通吧。