繁体   English   中英

Python返回并在wordcount函数中打印

[英]Python return and print in wordcount function

关心谁

当我运行return时,它不能像冠军一样工作; 当我运行print时,它的打印效果很好。 我做错了什么? 我的目标是返回列表中的值。 下面是返回函数:

def wordcount(mylist): #define a wordcount func
    for i in mylist: # create a first loop to iterate the list
        for c in "-,\_.": #create a sec loop to iterate the punctuation
            i=i.replace(c," ") # replace the punctuation with space
            a=len(i.split()) #split the str with space and calculate the len
        return (a)    


mylist=["i am","i,heart,rock,music","i-dig-apples-and-berries","oh_my_goodness"]
wordcount(mylist)

它返回2,我需要[2,4,5 3]。 下面是打印功能,它返回2 4 5 3.如何解决此问题? 我已经搜索了很长时间。 非常感谢!

def wordcount(mylist):
    for i in mylist:
        for c in "-,\_.":
            i=i.replace(c," ")
            a=len(i.split())
        print (a)    


mylist=["i am","i,heart,rock,music","i-dig-apples-and-berries","oh_my_goodness"]
wordcount(mylist)

当您return a ,您将在第一个退出函数的位置for迭代。

您可以使用list来累积结果:

def wordcount(mylist): #define a wordcount func
    ret = [] # list to accumulate results
    for i in mylist: # create a first loop to iterate the list
        for c in "-,\_.": #create a sec loop to iterate the punctuation
            i=i.replace(c," ") # replace the punctuation with space
            a=len(i.split()) #split the str with space and calculate the len
        ret.append(a) # append to list
    return ret # return results

或使用yield而不是return (它将创建一个generator ):

def wordcount(mylist): #define a wordcount func
    for i in mylist: # create a first loop to iterate the list
        for c in "-,\_.": #create a sec loop to iterate the punctuation
            i=i.replace(c," ") # replace the punctuation with space
            a=len(i.split()) #split the str with space and calculate the len
        yield a

为了从生成器中获取所有项目,请将其转换为list

list(wordcount(mylist))

暂无
暂无

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

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