从生成器中筛选出一些子集的最佳方法是什么。例如,我有一个字符串“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)
过滤一个简单而明显的条件,如“没有前导零”,它可以更有效地在组合建筑层完成。在
生成每一个组合的削减,只要它不是有趣的:
^{pr2}$只有那些没有前导零的片段:
递归步骤从不考虑以零开头的子字符串。在
一个常见的解决方案是在使用
yield
之前尝试过滤。我给你举了一个在屈服前过滤的例子:编辑:添加到生成器理解选项中
^{pr2}$相关问题 更多 >
编程相关推荐