(Notes to myself about Python 3)

Pinboard: /u:kittell/t:python


Update pip: pip install --upgrade pip

Update package: pip install [package_name] --upgrade

File handling

Read/write to files:

List/dict/set comprehensions

list_comp = [expr for val in collection if condition]
dict_comp = {key-expr : value-expr for value in collection if condition}
set_comp = {expr for value in collection if condition}


Load workbook: wb = load_workbook(filename=os.path.join(filepath, filename), read_only=True)

Loop over rows in worksheet:

for row in ws.rows:
    for col in row:
        v = row[col].value


# Draw an ellipse using parametric equations
# Source:
import numpy
from matplotlib import pyplot
from math import pi
x_0 = 1.0
y_0 = 0.5
a = 2.0    # semimajor axis
b = 1.5    # semiminor axis
t = numpy.linspace(0, 2 * pi, 100)
pyplot.plot(x_0 + a * numpy.cos(t), y_0 + b * numpy.sin(t))

# Draw a random path

import numpy
import matplotlib.pyplot as pyplot

# Add random number of points
import random
n = random.randint(5,10)
points = numpy.zeros((n,2))

for i in range(n):
    # Add random points
    a = random.randint(1,10)
    b = random.randint(1,10)
    points[i,:] = [a, b]

# Complete the loop: repeat first point as last point
# Appending to numpy arrays:
points = numpy.append(points, [points[0,:]], axis=0)

pyplot.plot(points[:,0], points[:,1])