Python返回并在wordcount函数中打印

时间:2018-05-03 08:47:17

标签: python printing return word-count

关注谁,

当我跑回来时,它不像冠军一样运作;当我运行打印时,它打印出来很好。我做错了什么?我的目标是返回列表中的值。以下是返回功能:

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)

1 个答案:

答案 0 :(得分:0)

执行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))