栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python中itertools.combinations()的使用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python中itertools.combinations()的使用

文章目录
  • itertools.combinations()
    • 作用
    • 示例
  • itertools.combinations_with_replacement()
    • 作用
    • 示例

itertools.combinations() 作用

来自 itertools 模块的函数 combinations(list_name, x) 将一个列表和数字 ‘x’ 作为参数,并返回一个元组列表,每个元组的长度为 ‘x’,其中包含x个元素的所有可能组合。列表中元素不能与自己结合,不包含列表中重复元素

示例
from itertools import combinations
a = ['h', 'y', 'k', 'q', 's']
    for i in combinations(a, 2):
        print(i)

输出

(‘h’, ‘y’)
(‘h’, ‘k’)
(‘h’, ‘q’)
(‘h’, ‘s’)
(‘y’, ‘k’)
(‘y’, ‘q’)
(‘y’, ‘s’)
(‘k’, ‘q’)
(‘k’, ‘s’)
(‘q’, ‘s’)

itertools.combinations_with_replacement() 作用

来自 itertools 模块的函数 combinations_with_replacement(list_name, x) 将一个列表和数字 x 作为参数,并返回一个元组列表,每个元组的长度为 x,其中包含x个元素的所有可能组合。使用此功能可以将列表中的一个元素与其自身组合。包含列表中重复元素

示例
    from itertools import combinations_with_replacement
    a = ['h', 'y', 'k']
    for i in combinations_with_replacement(a, 3):
        print(i)

输出

(‘h’, ‘h’, ‘h’)
(‘h’, ‘h’, ‘y’)
(‘h’, ‘h’, ‘k’)
(‘h’, ‘y’, ‘y’)
(‘h’, ‘y’, ‘k’)
(‘h’, ‘k’, ‘k’)
(‘y’, ‘y’, ‘y’)
(‘y’, ‘y’, ‘k’)
(‘y’, ‘k’, ‘k’)
(‘k’, ‘k’, ‘k’)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/886379.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号