python之itertools的排列组合相关

最近由于需要做一些排列组合的需要,本来没想到python自带库中会有这功能,还花了点时间写了下,后来翻看python标准库的时候,发现,这货居然直接提供了,而且还提供了几种形式,之间上代码:

import itertools

t_list = ["a","b","c","d"]

print("product")
for i in itertools.product(t_list,repeat=2):
    print(i)

print("permutations")    
for i in itertools.permutations(t_list, 2):
    print(i)

print("combinations")
for x in xrange(len(t_list)): 
    for i in itertools.combinations(t_list,x+1):
        print(i)
 
print("combinations_with_replacement")    
for i in itertools.combinations_with_replacement(t_list,2):
    print(i)

输入结果

product
('a', 'a')
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'a')
('b', 'b')
('b', 'c')
('b', 'd')
('c', 'a')
('c', 'b')
('c', 'c')
('c', 'd')
('d', 'a')
('d', 'b')
('d', 'c')
('d', 'd')
permutations
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'a')
('b', 'c')
('b', 'd')
('c', 'a')
('c', 'b')
('c', 'd')
('d', 'a')
('d', 'b')
('d', 'c')
combinations
('a',)
('b',)
('c',)
('d',)
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
('c', 'd')
('a', 'b', 'c')
('a', 'b', 'd')
('a', 'c', 'd')
('b', 'c', 'd')
('a', 'b', 'c', 'd')
combinations_with_replacement
('a', 'a')
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'b')
('b', 'c')
('b', 'd')
('c', 'c')
('c', 'd')
('d', 'd')

很漂亮。看来还是之前某位朋友说得对,python标准库,至少得过一遍,最好能有三遍并有对应的练习,这样玩,会玩的更嗨皮~

—EOF—

    原文作者:agentwx
    原文地址: https://segmentfault.com/a/1190000004209542
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞