Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested maps in Python 3

I want to transform my list list = [" a , 1 ", " b , 2 "] into a nested list [["a","1"],["b","2"]].

The following works:

f1_a = map(lambda x :[t.strip() for t in x.split(',',1)],list)

but this does not work with Python 3 (it does work with Python 2.7!):

f1_b = map(lambda x :map(lambda t:t.strip(),x.split(',',1)),list)

Why is that?

Is there a more concise way then f1_4 to achieve what I want?

like image 845
peer Avatar asked Jun 20 '15 09:06

peer


1 Answers

Python 3's map returns a map object, which you need to convert to list explicitly:

f1_b = list(map(lambda x: list(map(lambda t: t.strip(), x.split(',', 1))), lst))

Though in most cases you should prefer list comprehensions to map calls:

f1_a = [[t.strip() for t in x.split(',', 1)] for x in lst]
like image 143
vaultah Avatar answered Sep 22 '22 08:09

vaultah