python——combinations()所有组合

itertools.combinations()

简介

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

示例

from itertools import combinations
a = [2,1,5,5,3]
res=[]
for i in combinations(a,2):
    res.append(i)
print(res) #[(2, 1), (2, 5), (2, 5), (2, 3), (1, 5), (1, 5), (1, 3), (5, 5), (5, 3), (5, 3)]
print(len(res)) #10

itertools.combinations_with_replacement()

简介

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

示例

from itertools import combinations_with_replacement
a = [2,1,5,5,3]
res=[]
for i in combinations_with_replacement(a,2):
    res.append(i)
print(res) #[(2, 2), (2, 1), (2, 5), (2, 5), (2, 3), (1, 1), (1, 5), (1, 5), (1, 3), (5, 5), (5, 5), (5, 3), (5, 5), (5, 3), (3, 3)]
print(len(res)) #15
posted @ 2022-06-26 18:15  岸南  阅读(234)  评论(0)    收藏  举报