如果逻辑在 python 的数组上下文中不起作用

if logic not working in array context for python

我有一个函数,需要根据类型 t 应用不同的函数。我尝试了以下方法,但它在列表上下文中不起作用。

def compute(d, t='c'):
    """
    d is the computing variable
    t is the type, can be a list
    """
    if t == 'a':
        p = fa(d)
    elif t == 'b':
        p = fb(d)
    else:
        p = fc(d)
    return p

例如,t 可以是

t = ['a', 'b', 'a' , 'c', 'b']

应该return

p = [fa(d), fb(d), fa(d), fc(d), fb(d)]

有什么建议吗?

干杯, 麦克

这应该有效

def compute(d, t='c'):
    """
    d is the computing variable
    t is the type, can be a list
    """
    l = []
    for x in t:
        if t == 'a':
            l.append(fa(d))
        elif t == 'b':
            l.append(fb(d))
        else:
            l.append(fc(d))

    if len(l) == 1:
        return l[0]
    else:
        return l

compute(d, ['a', 'b', 'a' , 'c', 'b'])

它处理 t 中的所有内容,无论是单个项目还是列表。

请注意,它return是被调用函数的return值,而不是函数及其参数