我无法一次检查多个条件。
import itertools
def repeats(input1, input2):
return [int(dz) for dz in input1 if int(dz) in input2]
n_combs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
filters = [[[1, 2, 3, 6, 7, 8, 11, 12, 16, 17, 21, 22], [5]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [7]], [[20, 21, 22, 23, 24], [2]]]
combinacoes = itertools.combinations(n_combs, 15)
for comb in combinacoes:
for filtro, maxx in filters:
if len(repeats(filtro, comb)) in maxx:
print(comb)
基本上,我需要一种组合才能仅在以下情况下打印:
5
个项目:[1, 2, 3, 6, 7, 8, 11, 12, 16, 17, 21, 22]
7
个项目:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
2
个项目:[20, 21, 22, 23, 24]
上面的代码不会同时进行3个验证,这就是我所需要的。
答案 0 :(得分:0)
我假设您要对某个值应用任意数量的测试。
由于Python函数是一等公民,因此您可以拥有验证函数列表:
def iterable_contains_1(value):
return 1 in value
def iterable_contains_2(value):
return 2 in value
validators = [iterable_contains_1, iterable_contains_2]
然后,您可以调用所有验证:
for item in ([1, 2, 3], [2, 3, 4], [1, 3, 4], [3, 4, 5]):
if all(validator(item) for validator in validators):
print('do something with', item)
这将仅打印do something with [1, 2, 3]
,因为它是唯一通过两项测试的列表。
[编辑]
我认为您正在寻找set
。
def validator1(iterable):
return len(
set(iterable).intersection(
[1, 2, 3, 6, 7, 8, 11, 12, 16, 17, 21, 22]
)) >= 5
def validator2(iterable):
return len(
set(iterable).intersection(
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
)) >= 7
def validator3(iterable):
return len(
set(iterable).intersection(
[20, 21, 22, 23, 24]
)) >= 2
答案 1 :(得分:0)
我认为您的循环仅在filters
中的最后一个元素不符合您指定的条件的情况下才能正常工作。编辑它以包括较小的数字,就像我在下面所做的那样。另外,我减少了n_combs
中的元素数量,因此我的答案变得易于理解。这是因为出于演示目的,遍历25 combination 15
中超过300万个条目不是一个好主意。尝试在下面运行编辑后的版本,您会明白我在说什么。
import itertools
def repeats(input1, input2):
return [int(dz) for dz in input1 if int(dz) in input2]
n_combs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
filters = [[[1, 2, 3, 6, 7, 8, 11, 12, 16, 17, 21, 22], [5]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [7]], [[2, 4, 7,9], [2]]]
combinacoes = itertools.combinations(n_combs, 15)
for comb in combinacoes:
for filtro, maxx in filters:
if len(repeats(filtro, comb)) in maxx:
print(comb, maxx)
让我知道这是否可以解决您的问题。
答案 2 :(得分:0)
我找到了解决方法:
import itertools
def repeats(input1, input2):
return [int(dz) for dz in input1 if int(dz) in input2]
n_combs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
filters = [[[1, 2, 3, 6, 7, 8, 11, 12, 16, 17, 21, 22], [5]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [7]], [[20, 21, 22, 23, 24], [2]]]
combinacoes = itertools.combinations(n_combs, 15)
for comb in combinacoes:
if all([len(repeats(filtro, comb)) in qtd for filtro, qtd in filters]):
print(comb)
请记住,本文中使用的值只是示例,以简化和更好地理解逻辑。
现在该算法能够同时验证所有过滤器上的组合,并允许所有条件都满足一个条件。