2022-12-06
Python map
TIL
There is a built-in Python function called map
.
Python official documentation has it listed...
map(function, iterable, *iterables)
Return an iterator that applies function to every item of iterable, yielding the results.
But doesn't have any example code (maybe a good opportunity to contribute?)
Examples
>>> a, b = map(int, ["123", "007"]) >>> a 123 >>> b 7
>>> a, b = map(len, ["apple", "banana"]) >>> a 5 >>> b 6
>>> def add(n): ... return n + n >>> result = map(add, [1, 2, 3, 4]) >>> list(result) [2, 4, 6, 8]
Snippets from minho42, hyper-neutrino
line = "1-2,3-4" # How I did a, b, c, d = [int(x) for x in line.replace(",", " ").replace("-", " ").split()] # How it could've been done a, b, c, d = map(int, line.replace(",", "-").split("-"))