为标题道歉,我不知道我要做的事情的术语。
我有一个具有一系列嵌套循环的函数,它运行了很多次。循环有许多条件,无论它们是继续还是重新开始。
有时会调用此函数,使其需要满足某些稀有的条件。但是,要检查它们,我需要在我的代码中添加更多if语句。
以下是我所谈论的一个例子,我函数中的一些循环:
while 1:
for node in currset:
for (sum1, weight1, l1, r1) in pathdict[(0, node)]:
if sum1 & sum != sum1 or r1 == left or r1 == right or l1 == left:
continue
if level < connectright:
if l1 == right:
continue
elif l1 != right:
continue
for (sum2, weight2, l2, r2) in pathdict[(level, r1)]:
if sum2&sum != sum2:
continue
if l2 != left or l2 == right:
continue
andsum = sum1&sum2
if andsum != r1:
continue
现在,如果我有一个特殊情况,其中许多条件不再适用,我该怎么办?我现在看到它的方式,我可以1.)编写一个全新的函数,2。)重写整个代码块并将其放在另一个if语句之后,3。)添加一系列更多条件,或者4。 )编写一个在给定步骤检查我的条件的函数。
前两个选项看起来很笨重,但至少我的代码会很快。第三个似乎很糟糕,因为代码变得难以阅读,而且速度变慢。第四,我不确定,但似乎多次调用这些函数会减慢我的循环。
所以我的问题是,是否有某种方法可以编写“条件if语句”,根据传递给函数的变量,我可以做类似的事情:
if variable_passed == thing#1:
my_if_statement = (if level < connectright: continue)
else:
my_if_statement = (if level > connectright: continue)
这样,在开始循环之前,我可以在函数开始时轻松更改条件。
答案 0 :(得分:1)
您可以创建所有采用相同参数的函数列表,并使用参数的子集计算条件。
除非你有很多,或者正在产生条件,否则对我来说看起来有点太多了。
一个例子:
outer = [ # lambda parameters are all that could be used in any expression at point of call
(lambda sum, sum1, weight1, l1, r1, left, right, level, connectright:
sum1 & sum != sum1 or r1 == left or r1 == right or l1 == left),
(lambda sum, sum1, weight1, l1, r1, left, right, level, connectright:
level < connectright),
(lambda sum, sum1, weight1, l1, r1, left, right, level, connectright:
l1 != right),
# ... add extra outer loop conditions as necessary
]
inner1 = [ # lambda parameters are all that could be used in any expression at point of call
(lambda sum2, weight2, l2, r2, sum, sum1, weight1, l1, r1, left, right, level, connectright:
sum2&sum != sum2),
(lambda sum2, weight2, l2, r2, sum, sum1, weight1, l1, r1, left, right, level, connectright:
l2 != left or l2 == right),
# ... add extra inner loop conditions as necessary
]
inner2 = [ # lambda parameters are all that could be used in any expression at point of call
(lambda andsum, sum2, weight2, l2, r2, sum, sum1, weight1, l1, r1, left, right, level, connectright:
andsum != r1),
# ... add extra inner loop #2 conditions as necessary
]
while True:
for node in currset:
for (sum1, weight1, l1, r1) in pathdict[(0, node)]:
if any(f(sum, sum1, weight1, l1, r1, left, right, level, connectright)
for f in outer):
continue
for (sum2, weight2, l2, r2) in pathdict[(level, r1)]:
if any(f(sum2, weight2, l2, r2, sum, sum1, weight1, l1, r1, left, right, level, connectright)
for f in inner1):
continue
andsum = sum1&sum2
if any(f(andsum, sum2, weight2, l2, r2, sum, sum1, weight1, l1, r1, left, right, level, connectright)
for f in inner2):
continue