python 列表的排列组合

permutations/combinations/combinations_with_replacement

   items = ['a', 'b', 'c']
 from itertools import permutations
 for p in permutations(items):
 ...     print(p)
 ...
 ('a', 'b', 'c')
 ('a', 'c', 'b')
 ('b', 'a', 'c')
 ('b', 'c', 'a')
 ('c', 'a', 'b')
 ('c', 'b', 'a')
 
 
 
   for p in permutations(items, 2):
 ...     print(p)
 ...
 ('a', 'b')
 ('a', 'c')
 ('b', 'a')
 ('b', 'c')
 ('c', 'a')
 ('c', 'b')
 
 
 
   from itertools import combinations
 for c in combinations(items, 3):
 ...     print(c)
 ...
 ('a', 'b', 'c')
 
 
 
   for c in combinations(items, 2):
 ...     print(c)
 ...
 ('a', 'b')
 ('a', 'c')
 ('b', 'c')
 
 
 
   for c in combinations(items, 1):
 ...     print(c)
 ...
 ('a',)
 ('b',)
 ('c',)
 
 
 
   for c in combinations_with_replacement(items, 3):
 ...     print(c)
 ...
 ('a', 'a', 'a')
 ('a', 'a', 'b')
 ('a', 'a', 'c')
 ('a', 'b', 'b')
 ('a', 'b', 'c')
 ('a', 'c', 'c')
 ('b', 'b', 'b')
 ('b', 'b', 'c')
 ('b', 'c', 'c')
 ('c', 'c', 'c')
 
 
 

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励