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 3.6 性能测试框架Locust安装及使用方法(详解)

Python 3.6 性能测试框架Locust安装及使用方法(详解)

背景 Python3.6 性能测试框架Locust的搭建与使用 基础 python版本:python3.6 开发工具:pycharm Locust的安装与配置 点击“File”→“s...

基于tensorflow加载部分层的方法

一般使用 saver.restore(sess, modeldir + "model.ckpt") 即可加载已经训练好的网络,可是有时候想值使用部分层的参数,这时候可以选择在加载网...

实例讲解Python编程中@property装饰器的用法

取值和赋值 class Actress(): def __init__(self): self.name = 'TianXin' self.age = 5...

Python简单的制作图片验证码实例

Python简单的制作图片验证码实例

这里示范的验证码都是简单的,你也可以把字符扭曲 Python第三方库无比强大,PIL 是python的一个d第三方图片处理模块,我们也可以使用它来生成图片验证码 PIL安装 命令...

用python结合jieba和wordcloud实现词云效果

用python结合jieba和wordcloud实现词云效果

0x00 前言 突然想做一个漏洞词云,看看哪些漏洞比较高频,如果某些厂商有漏洞公开(比如ly),也好针对性挖掘。就选x云吧(镜像站 http://wy.hxsec.com/bugs.ph...