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

标签 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

最佳答案

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

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

关于python - 在python中递归删除列表(列表的列表的列表...)中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12752929/

相关文章:

无法破译输出

python - 随机快速排序中的最大递归深度误差

python - 使用 python 数据框中的两列(值、计数)绘制直方图

python - Pandas 数据框 : Find consecutive values and ignoring gaps of certain size

Python Flask SocketIO 在@socketio 上下文之外广播

python pandas如何将不同数据框中的其他值乘以列

python - 在 Windows 上部署 Python 包,编译依赖项,而不安装 Visual Studio?

python - 用 python 中可能的字典列表展平嵌套字典

c - 如何编写递归打印程序

python - 同时递归两个链表