简体   繁体   中英

Python return and print in wordcount function

To whom it concerns,

When I run return, it does not work like a champ; when I run print, it prints out good. 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]. Below is the print function, it returns 2 4 5 3. How can I fix this problem? 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.

You can use a list to accumulate results:

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 ):

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(wordcount(mylist))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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