繁体   English   中英

如何在python中返回列表?

[英]How to return a list in python?

我正在编写一个程序,该程序需要一个字符串列表并返回列表中每个字符串的长度。

def characters(nameLst):
    nameLst = ["Dan","jason","may","cole","Zhan"]
    outLst = []
    for i in range(len(nameLst)):
        outLst = outlst.append(len(nameLst))
    return (outLst) # should return [3, 5, 3, 4, 4]


nameLst = ["Dan","jason","may","cole","Zhan"]

def main():
    characters() 
main()

每次我运行程序时,都会出现错误:

characters() takes exactly 1 argument (0 given)

每次运行程序时,我都会收到一个错误: characters() takes exactly 1 argument (0 given)

这是调用characters()

characters() 

定义方式如下:

def characters(nameLst):

因此, python希望您像characters(names)一样调用它,而不是characters()

可能的解决方法是将nameLst内容移到main的作用域并将其传递(同样,您的characters函数执行的操作与您描述的有所不同。下面的修复):

 def characters(nameLst):
     outLst = []
     for name in nameLst:
         outlst.append(len(name))

     return outLst # should return [3, 5, 3, 4, 4]


 def main():
     nameLst = ["Dan","jason","may","cole","Zhan"]

     characters(nameLst) 

 if __name__ == '__main__':
     main()

定义方法characters ,您说它nameList一个名为nameList参数,但是当您在main方法内部调用它时,如果使用,则不会给它任何参数。

characters(nameList)

在您的主要方法中,这应该可以解决您的错误。

另外,您的代码不会为您提供nameList不同字符串的长度,而是会为您提供一个充满nameList长度的列表。 有了给定的列表,您将获得

[5, 5, 5, 5, 5]

因为添加到列表的表达式是len(nameList) ,当它应该是len(i)

最后, List.append()将追加到列表中,因此您无需使用=符号。 如果将行替换为:

outlst.append(len(nameLst[i]))

这应该给您正确的输出。

编辑:我刚刚意识到,您在characters功能内重新定义了nameLst 函数的内部和外部都不必具有nameLst 无论是定义characters不带任何参数,并定义nameLstcharacters ,或添加nameLst作为参数并没有定义它的函数内部。

旁注:这是您的函数的简单实现:

def characters(nameLst):
    return map(len, nameLst)

例:

>>> characters(["Dan","jason","may","cole","Zhan"])
[3, 5, 3, 4, 4]

我猜想,用map(len, ...)直接替换characters(...)是更好的解决方案... ;-)

您已经使用一个参数编写了字符(nameLst)。 因此,在调用函数时,请确保将列表传递给方法。

另外,您将需要在for循环之后返回(outLst)-这样,将返回整个列表,而不只是第一项。

该错误表示它的意思。 您声明了characters函数以一个名为nameLst的参数,但没有参数就调用了它。 要么改变

def characters(nameLst):

def characters():

有效地使nameLst成为局部变量,或在调用函数时将列表作为参数传递。

def characters(nameLst):
    outLst = []
    for i in range(len(nameLst)):
        outLst = outlst.append(len(nameLst))
    return (outLst)

def main():
    nameLst = ["Dan", "jason", "may", "cole", "Zhan"]
    characters(nameLst)

此外,最好将函数编写为列表理解:

def characters(nameLst):
    return [len(name) for name in nameLst]

请注意,您不要期望程序有任何输出,因为您从不调用print()

您的问题不是退货,而是电话。 您已将函数定义为采用一个参数,但是在调用它时尚未给它一个参数。

您定义一个函数characters ,它接受单个参数nameLst ,因此需要使用一个参数来调用它,如下所示:

def main():
    nameLst = ["Dan", "jason", "may", "cole", "Zhan"]
    result = characters(nameLst) # Save the returned list on the variable result
    print result # Print the result

main()

暂无
暂无

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

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