2

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

如果有意义的话,我编写的模块会单独返回基本案例的第一次出现,而不是整个递归对象。知道我做错了什么吗?

非常感谢!

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
4

2 回答 2

2

我认为您的意思是使用列表理解而不是return循环中的 a 。

else:
    print "base case didn't happen for", the_list
    return [remove_spaces_from_list_recursive(element) for element in the_list]
于 2012-10-05T19:40:19.487 回答
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)

以前,该函数只返回第一个元素,这就是它的结尾。

于 2012-10-05T19:40:54.977 回答