繁体   English   中英

Python 具有多个 arguments 的函数

[英]Python Functions with multiple arguments

我写了以下代码

def createv(dsn,vname,benchdsn,benchvar):
    #global grp
    for t in range(len(dsn)):
        w=dsn[vname].iloc[t]
        #print(w)
        for index in range(len(benchdsn)):
            #print(index)
            z = benchdsn[benchvar].iloc[index]
            #print(z)
            if w <= z:
                grp = z
                print(grp)
                break     
            else:
                continue
    return grp

recent_sample['carvaluegrp2']= createv(recent_sample,'CarValue',df6,'carvalueU')

问题在于,对于新创建的变量 carvaluegrp2,所有值都是相同的 - 这是来自 recent_sample 的 CarValue 的最后一个值。 我尝试使用 map() 和 apply() 函数,但出现语法错误。 我想要的只是具有适当的值 - function 为 CarValue 的每条记录返回 - 作为变量 carvaluegrp2 中的值。

您需要将 append 您的结果添加到这样的运行列表中:

def createv(dsn,vname,benchdsn,benchvar):
    result = []
    for t in range(len(dsn)):
        w=dsn[vname].iloc[t]
        #print(w)
        for index in range(len(benchdsn)):
            #print(index)
            z = benchdsn[benchvar].iloc[index]
            #print(z)
            if w <= z:
                grp = z
                print(grp)
                break     
            result.append(grp)
    return result

此外,您永远不需要else: continue 这与没有 else 的 if 语句相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM