Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a nested list with List Comprehension in Python?

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', 'World'], ['Goodbye', 'World']]
>>> [map(str.upper, x) for x in nested_list]
[['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']]

Can this be done with list comprehension alone (without using the map function)?

like image 870
kjfletch Avatar asked Aug 20 '09 14:08

kjfletch


4 Answers

Remember the Zen of Python:

There is generally more than one -- and probably several -- obvious ways to do it.**

** Note: Edited for accuracy.

Anyway, I prefer map.

from functools import partial
nested_list = map( partial(map, str.upper), nested_list )
like image 85
Stuart Berg Avatar answered Oct 13 '22 12:10

Stuart Berg


For nested lists you can use nested list comprehensions:

nested_list = [[s.upper() for s in xs] for xs in nested_list]

Personally I find map to be cleaner in this situation, even though I almost always prefer list comprehensions. So it's really your call, since either will work.

like image 26
Eli Courtwright Avatar answered Oct 13 '22 11:10

Eli Courtwright


Map is certainly a much cleaner way of doing what you want. You can nest the list comprehensions though, maybe that's what you're after?

[[ix.upper() for ix in x] for x in nested_list]
like image 3
KayEss Avatar answered Oct 13 '22 12:10

KayEss


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!

like image 2
Oldyoung Avatar answered Oct 13 '22 12:10

Oldyoung