Using itertools starmap¶
Let us understand the usage of starmap
. We will first create a collection with sales and commission percentage. Using that collection compute total commission amount. If the commission percent is None or not present, treat it as 0.
- Each element in the collection should be a tuple.
- First element is the sales amount and second element is commission percentage.
- Commission for each sale can be computed by multiplying commission percentage with sales (make sure to divide commission percentage by 100).
- Some of the records does not have commission percentage, in that case commission amount for that sale shall be 0
In [1]:
import itertools as iter
In [2]:
transactions = [(376.0, 8),
(548.23, 14),
(107.93, 8),
(838.22, 14),
(846.85, 21),
(234.84, None),
(850.2, 21),
(992.2, 21),
(267.01, None),
(958.91, 21),
(412.59, None),
(283.14, None),
(350.01, 14),
(226.95, None),
(132.7, 14)]
In [3]:
help(iter.starmap)
Help on class starmap in module itertools: class starmap(builtins.object) | starmap(function, iterable, /) | | Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given sequence. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature.
In [4]:
a = iter.starmap(lambda rec: rec[0] * rec[1] if rec[1] else 0, transactions)
In [5]:
for i in a: print(i) # This will fail. We have to pass elements from each tuple separately.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [5], in <cell line: 1>() ----> 1 for i in a: print(i) TypeError: <lambda>() takes 1 positional argument but 2 were given
In [6]:
iter.starmap(
lambda sale_amount, comm_pct:
round(sale_amount * comm_pct / 100, 2) if comm_pct else 0,
transactions
)
Out[6]:
<itertools.starmap at 0x7ff47df39cd0>
In [7]:
a = iter.starmap(
lambda sale_amount, comm_pct:
round(sale_amount * comm_pct / 100, 2) if comm_pct else 0,
transactions
)
In [8]:
for i in a:
print(i)
30.08 76.75 8.63 117.35 177.84 0 178.54 208.36 0 201.37 0 0 49.0 0 18.58
In [9]:
sum(iter.starmap(lambda sale_amount, comm_pct: (round(sale_amount * comm_pct / 100, 2)) if comm_pct else (0), transactions))
Out[9]:
1066.5