Python列表list排列组合 Python列表list排列组合操作示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python列表list排列组合 Python列表list排列组合操作示例

DreamLee0625   2021-03-30 我要评论

本文实例讲述了Python列表list排列组合操作。分享给大家供大家参考,具体如下:

排列

例如:

输入为

['1','2','3']和3

输出为

['111','112','113','121','122','123','131','132','133','211','212','213','221','222','223','231','232','233','311','312','313','321','322','323','331','332','333']

实现代码:

# -*- coding:utf-8 -*-
#! pyhton2
from itertools import product
l = [1, 2, 3]
print list(product(l, l))
print list(product(l, repeat=3))

上述代码运行输出:

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

组合

例如:

输入为

[1, 2, 3]和2

输出为

[1, 2], [1, 3], [2, 3] 不考虑顺序

实现代码:

# -*- coding:utf-8 -*-
#! pyhton2
from itertools import combinations
l = [1, 2, 3, 4, 5]
print list(combinations(l, 3))

上述代码运行输出:

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

希望本文所述对大家Python程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们