2012-10-05 67 views
2

我試圖從列表中的元素(可能列表中的列表等)中刪除所有空格,以遞歸方式刪除列表中的空格(列表中的列表...)python

我寫的模塊僅返回基本情況的第一次出現,而不是整個遞歸對象,如果這是有道理的。任何想法我做錯了什麼?

非常感謝!

def remove_spaces_from_list_recursive(the_list): #can deal with lists of lists of lists etc... 
     if type(the_list) is str: 
       print "base case happens", the_list 
       return the_list.replace(" ","") 

     else: 
      print "base case didn't happen for", the_list 
      for element in the_list: 
        return remove_spaces_from_list_recursive(element) 


data=['2', [['101', '103'], ['0', '0'], ['0', '0'], ['101', '101'], ['0', '0'], ['151', '157'], ['310', '310'], ['116', '116'], ['206', '206'], ['167', '169'], ['097', '097'], ['093', '104'], ['275', '275'], ['67', '73'], ['0', '0'], ['81', '83'], ['118', '139'], ['112', '112'], ['106', '106'], ['205', '207'], ['189', '189'], ['230', '230'], ['188', '188'], ['101', '134'], ['0', '0'], ['087', '099'], ['0', '0'], ['103', '105'], ['129', '139'], ['199', '202'], ['146', '146'], ['163', '163'], ['0', '0'], ['100', '103'], ['0', '0'], ['297', '298'], ['308', '311'], ['74', '78'], ['0', '0'], ['161', '163'], ['255', '255'], ['86', '86'], ['154', '157'], ['245', '250'], ['0', '0'], ['145', '149'], ['159', '163'], ['301', '301'], ['318', '326'], ['218', '221'], ['223', '226'], ['240', '240'], ['91', '93'], ['154', '154'], ['109', '109'], ['119', '119'], ['244', '244'], ['158', '176'], ['224', '224'], ['245', '245'], ['68', '71'], ['116', '119'], ['167', '167'], ['81', '81'], ['0', '0'], ['0', '0'], ['0', '0'], ['109', '118'], ['0', '0'], ['0', '0'], ['260', '260'], ['88', '88'], ['244', '246'], ['101', '101'], ['160', '163'], ['0', '0'], ['255', '255'], ['248', '248'], ['95', '95'], ['159', '163'], ['84', '91'], ['161', '161'], ['120', '120'], ['311', '311'], ['141', '153'], ['230', '232'], ['103', '105'], ['137', '162'], ['111', '111'], ['254', '258'], ['278', '278'], ['204', '208'], ['257', '257'], ['85', '85'], ['150', '150'], ['79', '79'], ['82', '86'], ['191', '194'], ['242', '245'], ['249', '249'], ['0', '0'], ['165', '168'], ['310', '310'], ['0', '0'], ['254', '257'], ['273', '276']]] 

data2=remove_spaces_from_list_recursive(data) 
print data2 
+0

'如果這是有道理的.' - 不,它不..你能更清楚嗎?你的預期產出是什麼? –

+1

您的基本情況返回一個字符串,並且您的遞歸步驟僅調用該函數。你無法獲得一個神奇的表單。 – NullUserException

回答

2

我想你的意思是在循環中使用列表理解而不是return

else: 
    print "base case didn't happen for", the_list 
    return [remove_spaces_from_list_recursive(element) for element in the_list] 
+0

這工作很好,謝謝! – Atticus29

2

您需要返回前,你的映射功能,每個元素:

def remove_spaces_from_list_recursive(the_list): #can deal with lists of lists of lists etc... 
     if isinstance(the_list, basestring): 
      print "base case happens", the_list 
      return the_list.replace(" ","") 
     else: 
      print "base case didn't happen for", the_list 
      return map(remove_spaces_from_list_recursive, the_list) 

之前,該函數返回第一個元素,那就是它的結束。

+0

非常感謝Blender!這很好,對我來說我做錯了什麼是有道理的。 – Atticus29