根据条件组合扩展行为

2024-04-25 12:39:13 发布

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

我正在用python编写一些代码,大致如下所示:

vals = [3, 4]
constraints = [5, 10]

def foo(val, constraint):
    return val <= constraint

def bar(x, y):
    # do stuff such as:
    print(x, y)

def baz(val):
    # transform val, such as by doing: 
    new_val = (val * 20 - 5) ** 2
    return new_val

bar(*vals)
if foo(vals[0], constraints[0]):
    bar(vals[0], baz(vals[1]))
if foo(vals[1], constraints[1]):
    bar(baz(vals[0]), vals[1])
if foo(vals[0], constraints[0]) and foo(vals[1], constraints[1]):
    bar(baz(vals[0]), baz(vals[1]))

我认识到这是一个代数关系,所以感觉应该有一个更简洁的方法来在代码中表示它。你知道吗

假设索引0上的foo返回的TrueA,索引1上的foo返回的TrueB。当A为真时应用的操作是a,同样B的操作是b。任何其他结果都是_。要生成的值集将是:

  |   _    |    A   |    B   |
-----------------------------
_ |  x,  y |  x,  y |  x,  y |
  |        | ax,  y |  x, by |
-----------------------------
  |  x,  y |  x,  y |  x,  y |
A | ax,  y | ax,  y |  x, by |
  |        |        | ax, by |
-----------------------------
  |  x,  y |  x,  y |  x, y  |
B |  x, by | ax,  y |  x, by |
  |        | ax, by |        |

有没有一种简洁(最好是通用)的方法来生成这些值,以便以后可以对它们进行map编辑或迭代?你知道吗


Tags: 代码byreturniffoodefasbar
1条回答
网友
1楼 · 发布于 2024-04-25 12:39:13

诚然,我不知道当你说你想要一个“在代码中用简洁的方式来表达这一点”是什么意思。如果您想概括这些函数,可以使用以下方法:

def foo(val, constraint):
    return val <= constraint

def bar(x, y):
    print x, y

def baz(val):
    return (val * 20 - 5) ** 2

def foobar(a, b)
    if a <= b:
        print a, b

def barbaz(a, b, c)
    if b <= c:
        print baz(a), b

def bazfoo(a, b, c, d)
    if a <= b and c <= d:
        print baz(a), baz(c)

vals = [3, 4]
constraints = [5, 10]

bar(*vals)

foobar(vals[0], constraints[0])
barbaz(vals[0], vals[1], constraints[1])
bazfoo(vals[0], constraints[0], vals[1], constraints[1])

相关问题 更多 >