Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

python - Transpose using a map() and lambda

I came across the following code:

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list(map(lambda *a: list(a), *l)) 

which returns: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

I don't quite follow how the values are being transposed. I understand that *l is used to unpack the list, after which I am a little uncertain. Any step by step explanation for this?

question from:https://stackoverflow.com/questions/65910327/transpose-using-a-map-and-lambda

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is what that code translates to for the given input:

list(map(lambda *a: list(a), *l)) 

l unpacks to:

list(map(lambda *a: list(a), [1, 2, 3], [4, 5, 6], [7, 8, 9])) 

The documentation of map explains what happens when it gets multiple iterable arguments like above:

If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.

So we can continue to break down as follows, knowing that in this case there are 3 iterable arguments, and so the mapping function will get three arguments when it gets called:

list(map(lambda x, y, z: list((x, y, z)), [1, 2, 3], [4, 5, 6], [7, 8, 9])) 

The mapping function returns a list, so:

list(map(lambda x, y, z: [x, y, z], [1, 2, 3], [4, 5, 6], [7, 8, 9])) 

The mapping function is called for each of the values in the iterable(s) in parallel, so:

list(((lambda x, y, z: [x, y, z])(1, 4, 7), 
      (lambda x, y, z: [x, y, z])(2, 5, 8), 
      (lambda x, y, z: [x, y, z])(3, 6, 9)))

These individual mappings result in:

list(([1, 4, 7], [2, 5, 8], [3, 6, 9]))

Which finally becomes a list:

[ [1, 4, 7], [2, 5, 8], [3, 6, 9] ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...