首页 > 解决方案 > How do I get all combinations of a list with repeating values

问题描述

I have a program that needs to get all possible combinations of items in a list, but what I have found so far doesn't give me what I need. From a list of say [1,2,3] I need the output,

(1)(2)(3)(1,1)(1,2)(1,3)(2,1)(2,2)(2,3)(3,1)(3,2)(3,3)

But all the solutions I've found give me an answer that doesn't repeat values, is there a library that can do this for me, because itertools doesn't give me the right output. Otherwise I'll just right a function myself.

标签: pythoncombinationspermutation

解决方案


您最初想要的结果只是列表的笛卡尔积本身:

my_list = [1,2,3]
list(itertools.product(my_list, my_list))
#=> [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

但是您将其编辑为包括 (1,)、(2,) 和 (3,)。在这种情况下,您可能会要求使用幂集 - 这是原始所有子集的集合。您可以使用此问题的答案,但请注意,结果将包括空列表和完整的原始列表。


推荐阅读