简体   繁体   English

Python返回并在wordcount函数中打印

[英]Python return and print in wordcount function

To whom it concerns, 关心谁

When I run return, it does not work like a champ; 当我运行return时,它不能像冠军一样工作; when I run print, it prints out good. 当我运行print时,它的打印效果很好。 What did I do wrong? 我做错了什么? My goal is to return the value in a list. 我的目标是返回列表中的值。 Below is the return function: 下面是返回函数:

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)

It returns 2, I need [2,4,5 3]. 它返回2,我需要[2,4,5 3]。 Below is the print function, it returns 2 4 5 3. How can I fix this problem? 下面是打印功能,它返回2 4 5 3.如何解决此问题? I have been searching for quite a while. 我已经搜索了很长时间。 Thanks a lot! 非常感谢!

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)

When you do return a , you exit the function at the first for iteration. 当您return a ,您将在第一个退出函数的位置for迭代。

You can use a list to accumulate results: 您可以使用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

or use yield instead of return (it will create a generator ): 或使用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

In order to get all the items from a generator, convert it to list : 为了从生成器中获取所有项目,请将其转换为list

list(wordcount(mylist))

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

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