简体   繁体   中英

How does the following map function work?

>>>uneven = [['a','b','c'],['d','e'],['g','h','i']]
>>>map(None,*uneven)

O/P: [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]

The code above can be used for finding transpose of a matrix. However iam unable to understand how it WORKS.

When using the * operator, the list is broken up into position arguments for the map. This is what you're actually running:

>>> map(None, ['a','b','c'], ['d','e'], ['g','h','i'])

When you pass multiple iterables to map , then the function (in this case None ) is applied to every iterable in parallel. It processes 'a', 'd', 'g' first, and so on.

Edit: As pointed out by Jon below, when you pass in None as the map function, it gets special cased to be the identity function, ie lambda id: id . This special casing of None 's use in map has been removed in Python 3.

map(function, sequence[, sequence, ...]) -> list

from the documentation of map

If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length.

If the function is None, return a list of the items of the sequence

Using sequence with * operator zip it according to the position of items in sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM