python列表、字符串全排列、组合

无嵌套列表全排列

import itertools

a = [1,2,3]
b = list(itertools.permutations(a, len(a)))
print(b)
#结果:[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

len(a)是a列表的长度,这个是参数是可变的只要>=0且<=len(a)即可

import itertools

a = [1,2,3]
b = list(itertools.permutations(a, 2))
print(b)
#结果:[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

或者还可以这样实现全排列

from itertools import permutations

a = [1,2,3]
print(list(permutations(a)))
#结果:[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

字符串全排列

将字符串转为列表先

import itertools

str1 = "123"
a = list(str1)
list1 = []
b = list(itertools.permutations(a, len(str1)))
for i in b:
    list1.append("".join(i))
print(b)
print(list1)
#结果:[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
#结果:['123', '132', '213', '231', '312', '321']

嵌套列表全排列

from itertools import product

a = [[1, 3, 11], [2, 4, 6], [7, 8, 9]]
b = list(product(*a))
print(b)
#结果:[(1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (3, 2, 7), (3, 2, 8), (3, 2, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9), (11, 2, 7), (11, 2, 8), (11, 2, 9), (11, 4, 7), (11, 4, 8), (11, 4, 9), (11, 6, 7), (11, 6, 8), (11, 6, 9)]

组合

import itertools

a = list(itertools.combinations([1, 2, 3, 4], 3))
print(a)
#结果:[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
import itertools

a = list(itertools.combinations([1, 2, 3, 4], 2))
print(a)
#结果:[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值