重复排列和可能值之间的规则

2024-04-24 01:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python2.6并找到了函数

[in] a=[[1,2,3],[1,2,3]]
[in] b=list(itertools.product(*a))

其中a是一个列表列表,结果是一个列表,每个可能的组合都有元组,从a中的每个列表中取一个值

[out]  [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

当我开始处理一个包含20个列表的列表时,问题就来了(结果是3**20个不同的元组并溢出内存)。 为了避免这些问题,我希望在生成之前或期间创建所有元组之后应用我正在应用的约束。 这些约束条件包括:

  • 总是连续两个2
  • 1的40%
  • 不是1后3或3后1 ... 你知道吗

有人能帮我用一个高级功能来做这类事情吗?你知道吗


Tags: 函数内存in功能列表productout事情
1条回答
网友
1楼 · 发布于 2024-04-24 01:16:56

itertools的一个优点是它们不占用太多内存,只返回一个迭代器。 然后可以执行以下操作:

def valid_combination(combination):
    # Do whatever test you want here
    pass

def product_with_validation(validation_func, *element_list):
    for combination in itertools.product(*element_list):
        if validation_func(combination):
            yield combination

all_combinations = list(product_with_combo(product_with_validation, [1,2,3],[1,2,3])

带有组合的产品还返回一个迭代器,节省了大量内存。你知道吗

例如:

import itertools

def valid_combination(combination):
    return len(combination)>0 and combination[0]==2

def product_with_validation(validation_func, *element_list):
    return (combination for combination in itertools.product(*element_list) 
           if valid_combination(combination))
print list(product_with_validation(valid_combination, range(10), range(10)))

结果:

[(2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9)]

附言:

itertools有一个函数,它的功能与产品的验证功能几乎相同:ifilter,您可能需要使用它,因为它可能比自定义编写的要快得多。你知道吗

相关问题 更多 >