Python Functions

Sort

alist.sort(key=lambda x: x.foo)

# Sort and return index
sorted(range(len(alist)), key=lambda k: alist[k])

# Sort by multiple attributes (age then name)
sorted_by_multiple = sorted(people, key=lambda p: (p.age, p.name))
print(f"Sorted by age then name: {sorted_by_multiple}")

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))


Itertools

p, q, …

(p[0], q[0]), (p[1], q[1]), …

zip_longest('ABCD', 'xy',fillvalue='-') β†’ Ax By C- D-

p [,func]

p0, p0+p1, p0+p1+p2, …

accumulate([1,2,3,4,5]) β†’ 1 3 6 10 15

Functools

Last updated