2016-04-03 57 views
0

append vs. extend返回的列表。我在這裏得到了答案,我只需要使用extend關鍵字而不是append。合併由`re.findall()`

def extractDollar(line): 
     global mainList 
     temp=[] 

     #lowercasing all the string 
     line=line.lower() 

     #storing all word starting with $ in a line in temp 
     #then adding that to existing list mainList 
     #to form a single list and removing empty value 
     temp= re.findall(r'$\w+',line) 

     mainList=mainList+[j for i in zip(mainList,temp) for j in i] 
     mainList= filter(None, mainList) 

     return line 

我有一個多個字符串的文件;每個字符串都有以$開頭的單詞,並且我希望將以$開頭的所有單詞作爲單個List(mainList)存儲在文件中。
我寫了這個函數來逐行讀取文件。我得到的temp數組中填充了以$開頭的所有值,但不能將re.findall返回的所有單個列表添加爲單個主列表。

回答

0

嘗試reduce(sum, line)

def extractDollar(line): 
     global mainList 
     temp=[] 

     #lowercasing all the string 
     line=line.lower() 

     #storing all word starting with $ in a line in temp 
     #then adding that to existing list mainList 
     #to form a single list and removing empty value 
     temp= re.findall(r'$\w+',line) 

     mainList=mainList+[j for i in zip(mainList,temp) for j in i] 
     mainList= filter(None, mainList) 

     return reduce(sum,line) 
+0

我得到了答案,但感謝。我只需要使用擴展。所以mainlList.extend(temp) –