Обложка канала

Библиотека Python разработчика

20835 @BookPython

Библиотека Python разработчика. Книги по программированию на Python.

Библиотека Python разработчика

4 года назад
Открыть в
The map function calls another function for every element of some iterable. That means that function should accept a single value as an argument: In : list(map(lambda x: x ** 2, [1, 2, 3])) Out: [1, 4, 9] However, if each element of the iterable is tuple, then it would be nice to pass each element of that tuple as a separate argument. It was possible in Python 2, thanks to the tuple parameter unpacking (note the parentheses): >>> map(lambda (a, b): a + b, [(1, 2), (3, 4)]) [3, 7] In Python 3, this feature is gone, but there is another solution. itertools.starmap unpacks tuple for you, as though a function is called with a star: f(*arg) (hence the function's name): In [3]: list(starmap(lambda a, b: a + b, [(1, 2), (3, 4)])) Out[3]: [3, 7]