Python中itertools.combinations

Python中itertools.combinations,第1张

文章目录
  • 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’)

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/920925.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存