我已经在这里编写了代码,但是它花费了很多时间。我需要进一步优化它。这里的 k 是变化的,它可以是 2 或 3 或 4,取决于用户。请帮帮我。
from itertools import combinations
def get_all_combinations(input_list, k):
for item in combinations(input_list, k):
yield list(set(list(item)))
input_list = [1, 2, 1, 2, 3]
k = 3
lst = []
for i in range(1, k + 1):
for item in get_all_combinations(input_list, i):
if len(item) > i - 1:
lst.append(item)
print(len(lst))
>>17
#[[1], [2], [1], [2], [3], [1, 2], [1, 2], [1, 3], [1, 2], [2, 3], [1, 2], [1, 3], [2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
最佳答案
试试这个:
>>> input_list = [1, 2, 1, 2, 3]
>>> k = 3
>>> [list(set(el)) for i in range(1, k+1) for el in itertools.combinations(input_list, i) if len(set(el))>i-1]
[[1], [2], [1], [2], [3], [1, 2], [1, 2], [1, 3], [1, 2], [2, 3], [1, 2], [1, 3], [2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
https://stackoverflow.com/questions/57944957/
相关文章:
c++ - 使用 ioctl 在 C++ 中以编程方式添加路由
python - 使用 image_slicer.py 将切片加入完整图像
node.js - 如何在 Node SOAP 中发送原始 XML 请求
java - 从 jlink 图像创建所有包含 windows 可执行文件
azure-functions - Azure 函数无法在 Azure 门户中下载 PowerShe
npm - 无法在 Nexus Repository Manager 2.10 上发布库
javascript - 如何转到 Epubjs 中的特定页面
reactjs - React-Select 从 1.x 升级到 3.0.4 - 未显示选定值