过滤掉一代人

2024-10-02 12:26:04 发布

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

从生成器中筛选出一些子集的最佳方法是什么。例如,我有一个字符串“1023”,希望生成每个数字的所有可能的组合。所有组合将是:

['1', '0', '2', '3']
['1', '0', '23']
['1', '02', '3']
['1', '023']
['10', '2', '3']
['10', '23']
['102', '3']
['1023']

我对任何项上包含前导0的子集不感兴趣,因此有效的是:

^{pr2}$

我有两个问题。在

1)如果使用生成器,什么是过滤掉前导零的最佳方法。目前,我生成所有的组合,然后循环通过它,只有当子集有效时才继续。为了简单起见,我只打印示例代码中的子集。假设所创建的生成器非常长,或者它包含许多无效的子集,那么循环整个生成器几乎是一种浪费。当生成器看到无效项(前导为零)时,有没有办法停止生成器,然后过滤掉“allCombinations”

2)如果不存在上述情况,有什么更好的方法来生成这些组合(忽略前导零的组合)。在

使用生成器的代码:

import itertools

def isValid(subset):         ## DIGITS WITH LEADING 0 IS NOT VALID
    valid = True
    for num in subset:
        if num[0] == '0' and len(num) > 1:
            valid = False
            break

    return valid

def get_combinations(source, comb):
    res = ""
    for x, action in zip(source, comb + (0,)):
        res += x
        if action == 0:
            yield res
            res = ""

digits = "1023"
allCombinations = [list(get_combinations(digits, c)) for c in itertools.product((0, 1), repeat=len(digits) - 1)]


for subset in allCombinations:   ## LOOPS THROUGH THE ENTIRE GENERATOR
    if isValid(subset):
        print(subset)

Tags: 方法代码inforifdefresnum
2条回答

过滤一个简单而明显的条件,如“没有前导零”,它可以更有效地在组合建筑层完成。在

def generate_pieces(input_string, predicate):
    if input_string:
        if predicate(input_string):
            yield [input_string]
        for item_size in range(1, len(input_string)+1):
            item = input_string[:item_size]
            if not predicate(item):
                continue
            rest = input_string[item_size:]
            for rest_piece in generate_pieces(rest, predicate):
                yield [item] + rest_piece

生成每一个组合的削减,只要它不是有趣的:

^{pr2}$

只有那些没有前导零的片段:

>>> list(generate_pieces('10002', lambda x: not x.startswith('0')))
[['10002'], ['1000', '2']]

递归步骤从不考虑以零开头的子字符串。在

一个常见的解决方案是在使用yield之前尝试过滤。我给你举了一个在屈服前过滤的例子:

import itertools

def my_gen(my_string):

    # Create combinations
    for length in range(len(my_string)):
        for my_tuple in itertools.combinations(my_string, length+1):

            # This is the string you would like to output
            output_string = "".join(my_tuple)

            # filter here:
            if output_string[0] != '0':
                yield output_string


my_string = '1023'
print(list(my_gen(my_string)))

编辑:添加到生成器理解选项中

^{pr2}$

相关问题 更多 >

    热门问题