为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Python中生成列表的所有排列

如何在Python中生成列表的所有排列

SMILET 2019-05-27 13:13:42
如何在Python中生成列表的所有排列如何在Python中生成列表的所有排列,与该列表中的元素类型无关?例如:permutations([])[]permutations([1])[1]permutations([1, 2])[1, 2][2, 1]permutations([1, 2, 3])[1, 2, 3][1, 3, 2][2, 1, 3][2, 3, 1][3, 1, 2][3, 2, 1]
查看完整描述

4 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

以下代码仅适用于Python 2.6及更高版本


一,进口itertools:


import itertools

排列(订单事宜):

print list(itertools.permutations([1,2,3,4], 2))

[(1, 2), (1, 3), (1, 4),

(2, 1), (2, 3), (2, 4),

(3, 1), (3, 2), (3, 4),

(4, 1), (4, 2), (4, 3)]

组合(顺序无关紧要):

print list(itertools.combinations('123', 2))

[('1', '2'), ('1', '3'), ('2', '3')]

笛卡尔积(有几个迭代):

print list(itertools.product([1,2,3], [4,5,6]))

[(1, 4), (1, 5), (1, 6),

(2, 4), (2, 5), (2, 6),

(3, 4), (3, 5), (3, 6)]

笛卡儿积(一个可迭代的本身):

print list(itertools.product([1,2], repeat=3))

[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),

(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]


查看完整回答
反对 回复 2019-05-27
?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

def permutations(head, tail=''):
    if len(head) == 0: print tail    else:
        for i in range(len(head)):
            permutations(head[0:i] + head[i+1:], tail+head[i])

称为:

permutations('abc')


查看完整回答
反对 回复 2019-05-27
  • 4 回答
  • 0 关注
  • 2464 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信