[英]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.