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ループ内ではなくリスト内包表記を使用するつもりだと思います。

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 に答える