Python is full of cool shortcuts that I can't seem to remember when I need to, so I'm gonna document them here.
Default dictionary
This can be used to avoid having to check for existence of keys by providing default values.
from collections import defaultdict
from collections import defaultdict
counter = defaultdict(int) # Default to integer set to 0
for akey in alist:
counter[akey] += 1
Or one to many lists.
from collections import defaultdict
onetomany = defaultdict(list)
for akey, anitem in acollection:
onetomany[akey].append(anitem)
Output Latex Formats
print r"\begin{tabular}{|l|l|}"
print r"\hline"
print r"MAC & IP\\"
print r"\hline"
for snd,rcv in ans:
print rcv.sprintf(r"%Ether.src% & %ARP.psrc%\\")
print r"\hline"
print r"\end{tabular}"
List Comprehensions
Convert a string to an array of ASCII characters
[ord(ch) for ch in "Hallo"]
Nested(?) access to list
in: r = [1,2]
in: [ (x, y) for x in r for y in r ]
out: [(1, 1), (1, 2), (2, 1), (2, 2)]
Create various shapes and sizes of sets of points
from random import random as rnd
_2x1 = [rnd() for _ in range(2)]
_3x2 = [[rnd() for _ in range(2)] for _ in range(3)]
_4x3x2 = [[[rnd() for _ in range(2)] for _ in range(3)] for _ in range(4)]
ThreePoints = [[rnd(),rnd()] for _ in range(3)]
Strange Objects
Evaluate completely dynamic code
a=5
b="a*a"
eval(b)
25
Language Features
Built in list iteration
# x is a list of integers.
In : x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In : x[::1] # Every item
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]In : x[::2] # Get every 2nd item
Out: [0, 2, 4, 6, 8]In : x[::3] # Every 3rd item
Out: [0, 3, 6, 9]
# Backwards
In : x[::-1]Out: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]In : x[::-2]Out: [9, 7, 5, 3, 1]
Decorators to dynamically add functionality to class instance from
StackOverflow
class Pizza(object):
def __init__(self):
self.toppings = []
def __call__(self, topping):
# Use '@instance_of_pizza' before a function def and the function gets passed onto 'topping'
self.toppings.append(topping())
def __repr__(self):
return str(self.toppings)
myPizza = Pizza()
@myPizza
def cheese():
return 'cheese'
@myPizza
def sauce():
return 'sauce'
print myPizza
# ['cheese', 'sauce']
Iterators allow objects to work with for statements, require 'next' method
class PizzaFactory(object):
def __init__(self):
self.orders = {1:'ted", 2:"joe"}
def __iter__(self):
return OrderIterator(self)
class OrderIterator(object):
def __init__(self, container):
self.items = container
self.index = 0
def next(self):
if self.index >= len(self.items): raise StopIteration
ret = self.items[self.index]
self.index += 1
return ret
# pf = PizzaFactory()
for order in pizza: print order
1:ted
2:joe
Generators allow function to return intermediate values
def fib(n):
a = 0
yield a
b = 1
yield b
while b < n:
a, b = b, a + b
yield b
# for e in fib(5): print e
0
1
1
2
3
5
Ternary operator
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
print factorial(5)