python - 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.
解决方案
您最初想要的结果只是列表的笛卡尔积本身:
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,)。在这种情况下,您可能会要求使用幂集 - 这是原始所有子集的集合。您可以使用此问题的答案,但请注意,结果将包括空列表和完整的原始列表。
推荐阅读
- android - 在 Android Studio 中输入 IP 地址并返回该 IP 地址的位置
- reactjs - 如何在 Material UI 按钮上将空值作为道具传递
- python - Python中nD一般线与凸包的交点
- c - 如何在字符串中复制一个字母?
- java - Ant:错误:找不到符号:符号:类服务器:位置:类 SslContextFactory。即使 JAR 在类路径中
- r - 提取第一个和第三个句点之间的字符
- python - 用白色 OpenCv Python 填充轮廓外部
- scrapy - 如何绕过被“Scrapy”阻止
- c++ - C++ MFC 跟踪事件调用
- php - 简单的验证码表单动作验证