8

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?

2 Answers 2

13

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Why are you suggesting "x.replace" over "x.strip"?
@JohnPrawyn: to get rid of one loop: [t.strip() for t in x.split(',', 1)] would become x.replace(' ', '').split(','). On the other hand, now I see that the suggestion is restricted to the data in the question and will fail on more complex examples. I removed it from my answer.
-1

Python3 map function returns map object and that object need to typecast in list.

num = [" a , 1 ", " b , 2 "]

list1 = list(map(lambda x:x.split(','), num))

print(list1)

Output:

[[' a ', ' 1 '], [' b ', ' 2 ']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.