简体   繁体   English

从Python列表中仅生成某些组合

[英]Generate only certain combinations from a list in Python

I have used the following script to generate all combinations: 我已使用以下脚本生成所有组合:

import itertools
x = 7
my_list = range(1, 11)
for k in [x]:
   for sublist in itertools.combinations(my_list, k):
      print sublist

For the second part I will take 6 random elements from range(1, 11). 对于第二部分,我将从range(1,11)中抽取6个随机元素。 Let's call them my_second_list. 我们称它们为my_second_list。 I need to generate the minimum number of combinations of my_list in order to obtain at least one combination to include let's say 5 elements from my_second_list. 我需要生成最小数量的my_list组合,以获取至少一个组合,比如说my_second_list中包含5个元素。

Any ideas on how to do that? 关于如何做到这一点的任何想法?

import itertools

x = 7
my_list = range(1,11)

for k in [x]: # isn't this just 7?
    your_output = (combination for combination in itertools.combinations(my_list,k) if all(element in combination for element in [1,2,3,4,5]))

It's ugly as heck, but that's how I'd do it (if I'm understanding your question correctly. You're trying to get only those combinations that contain a certain subset of items, right? If you want all combinations BEFORE and INCLUDING that first combination that contains the subset of items, I'd do: 很难理解,但这就是我的处理方式(如果我正确地理解了您的问题。您正在尝试仅获取包含某些项目子集的组合,对吗?如果您想要所有组合,包括之前和之后)包含项子集的第一个组合,我会做:

accumulator = list()
subset = [1,2,3,4,5] # or whatever
for k in [x]:
    for combination in itertools.combinations(my_list,k):
        accumulator.append(combination)
        if all(el in combination for el in subset):
            break

Depending on your exact use case you may want to consider defining subset as a set (eg {1,2,3,4,5} ) and do subset.issubset(set(combination)) but it's hard to tell if that's better or not without doing some profiling. 根据您的确切用例,您可能需要考虑将subset定义为一个set (例如{1,2,3,4,5} )并执行subset.issubset(set(combination))但很难确定这是更好还是并非没有任何分析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM