Mapping a nested list with List Comprehension in Python?

前端 未结 5 537
自闭症患者
自闭症患者 2020-12-11 03:28

I have the following code which I use to map a nested list in Python to produce a list with the same structure.

>>> nested_list = [[\'Hello\', \'Wo         


        
5条回答
  •  感情败类
    2020-12-11 04:05

    Here is solution for nested list that has arbitrary depth:

    def map_nlist(nlist=nlist,fun=lambda x: x*2):
        new_list=[]
        for i in range(len(nlist)):
            if isinstance(nlist[i],list):
                new_list += [map_nlist(nlist[i],fun)]
            else:
                new_list += [fun(nlist[i])]
        return new_list
    

    you want to upper case all you list element, just type

    In [26]: nested_list = [['Hello', 'World'], ['Goodbye', [['World']]]]
    In [27]: map_nlist(nested_list,fun=str.upper)
    Out[27]: [['HELLO', 'WORLD'], ['GOODBYE', [['WORLD']]]]
    

    And more important, this recursive function can do more than this!

    I am new to python, feel free to discuss!

提交回复
热议问题