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

yipeiwu_com6年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

Python编译成.so文件进行加密后调用的实现

pyc的破解相对容易,使用cython将python文件编译成.so文件,能在一定程度上增强python源码的私密性。 编译成.so文件 环境准备:cython 测试脚本准备:test....

python实现文件路径和url相互转换的方法

本文实例讲述了python实现文件路径和url相互转换的方法。分享给大家供大家参考。具体实现方法如下: import urllib pathname = 'path/to/file...

Python中list列表的一些进阶使用方法介绍

判断一个 list 是否为空 传统的方式: if len(mylist): # Do something with my list else: # The list is e...

Python中的 ansible 动态Inventory 脚本

Python中的 ansible 动态Inventory 脚本

1.Ansible Inventory  介绍; Ansible Inventory 是包含静态 Inventory 和动态 Inventory 两部分的,静态 Invento...

python顺序执行多个py文件的方法

假如我要执行code目录下的python程序,假设该目录下有1.py,2.py,3.py,4.py四个文件,但是我想执行1.py,2.py,4.py,则可在该目录下创建一个python文...