在python中递归删除列表中的空格(列表列表列表...)

时间:2012-10-05 19:36:12

标签: python recursion

我正在尝试从列表列表中删除所有空格(可能是列表列表等等)。

我编写的模块只返回基本案例的第一个外观,而不是整个递归对象,如果这有意义的话。知道我做错了吗?

非常感谢!

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

2 个答案:

答案 0 :(得分:2)

我认为你的意思是在循环中使用列表推导而不是return

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

答案 1 :(得分: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)

之前,该函数只返回第一个元素,即它的结尾。

相关问题