Functools module


In [ ]:
from operator import add
from functools import reduce

print(list(reduce(add,
                  [[1, 2, 3], [4, 5], [6], [7, 8, 9, 10]])))
print(set(reduce(add,
                  [[1, 2, 3], [4, 5], [6], [7, 8, 9, 10]],
                  [0])))
print(list(reduce(lambda x, y: [y, x],
                  ((1, 2), (11, 12, 13), (21,), (31, 32, 33, 34), (41, 42, 43)))))
print(tuple(reduce(lambda x, y: [y, x],
                  ((1, 2), (11, 12, 13), (21,), (31, 32, 33, 34), (41, 42, 43)),
                  (0,))))

In [ ]:
from functools import cmp_to_key

def cmp(x, y):
    if x == y:
        return 0
    if x % 10 < y % 10 or x % 10 == y % 10 and x // 10 < y // 10:
        return -1
    return 1

print(sorted([10, 11, 12, 30, 31, 32, 20, 21, 22], key = cmp_to_key(cmp)))

In [ ]:
from functools import namedtuple

Point = namedtuple('Point', ['x', 'y', 'z'])
p1 = Point(11, 12, 13)
p2 = Point(21, z = 23, y = 22)
print(p1)
print(p2)
print()

print(p1[0], p1[1], p1[2])
print(p2.x, p2.y, p2.z)

In [ ]:
from functools import partial

def f(w, x, y, z, a, b, c, d):
    print(w, x, y, z, a, b, c, d)
    
g = partial(f, 1, 2, b = 6,  d = 8)

g(3, 4, c = 7, a = 5)