循环,python,定义一系列变量和函数

2024-09-30 20:35:21 发布

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

我是Python新手,很难理解如何使用循环。你知道吗

有没有人能帮我在循环/列表中写下面的代码,这会短得多?你知道吗

def a1(self):
    if aorb1 == 1:
        return texta1
    return textb1

def a2(self):
    if aorb2 == 1:
        return texta2
    return textb2

def a3(self):
    if aorb3 == 1:
        return texta3
    return textb3

非常感谢。你知道吗


Tags: 代码selfa2列表returnifdefa1
2条回答

您可以在传递ab的地方生成lambda,如下所示:

my_funcs = []
for i in range(1,4):
    func = lambda a, b: textas[i] if a == 1 or b == 1 else textbs[i]
    my_funcs.append(func)

您可以这样调用这样的函数:

my_funcs[0](0,1)  # this does the same as your function a1

我不知道你想要什么。这可以存储在字典中,就像我在上面的示例中所做的那样。你知道吗

我可以尝试一下你要去的方向,并提供一定程度的指导,但我怀疑如果没有更多的信息,我不会去正确的方向。你知道吗

首先,不需要self作为参数。这只适用于对象。你知道吗

接下来,您需要提供函数中使用的变量作为参数。看起来您试图使用ab而没有声明它们。你知道吗

def a1(a, b)
    if a == 1:
        return texta
    elif b == 1:
        return textb

小心别错过任何案子。如果a = 0b = 0呢?然后这个函数将返回None。你知道吗

最后,我不确定你到底想用这个循环做什么,但也许是这样的?你知道吗

# assign a and b values somewhere
a = 1
b = 0

# save the functions in a list
my_functions = [a1, a2, a3]

# execute each function with the parameters `a` and `b`
for f in my_functions:
    result = f(a, b)
    x.append(result)

这将产生一个包含函数执行结果的列表,其中包含参数ab。希望能提供更多帮助,但我们需要更多信息。或许上述情况会刺激这一点。你知道吗

相关问题 更多 >