Skip to content

Instantly share code, notes, and snippets.

@Averroes
Averroes / somefile.txt
Created April 10, 2015 14:09
keeping the last n items
=== Keeping the Last N Items
==== Problem
You want to keep a limited history of the last few items seen
during iteration or during some other kind of processing.
==== Solution
Keeping a limited history is a perfect use for a `collections.deque`.
@Averroes
Averroes / example1.py
Created April 10, 2015 14:10
mapping names to sequence elements
# example.py
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
def compute_cost(records):
total = 0.0
for rec in records:
s = Stock(*rec)
@Averroes
Averroes / example.py
Created April 10, 2015 14:10
removing duplicates from a sequence while maintaining order
# example.py
#
# Remove duplicate entries from a sequence while keeping order
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
@Averroes
Averroes / example2.py
Created April 10, 2015 14:11
removing duplicates from a sequence while maintaining order
# example2.py
#
# Remove duplicate entries from a sequence while keeping order
def dedupe(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
@Averroes
Averroes / example.py
Created April 10, 2015 14:12
sort a list of dictionaries by a common key
# example.py
#
# Sort a list of a dicts on a common key
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]
@Averroes
Averroes / example.py
Created April 10, 2015 14:12
sort objects without native comparison support
from operator import attrgetter
class User:
def __init__(self, user_id):
self.user_id = user_id
def __repr__(self):
return 'User({})'.format(self.user_id)
# Example
users = [User(23), User(3), User(99)]
@Averroes
Averroes / example.py
Created April 10, 2015 14:13
transforming and reducing data at the same time
# example.py
#
# Some examples of using generators in arguments
import os
files = os.listdir(os.path.expanduser('~'))
if any(name.endswith('.py') for name in files):
print('There be python!')
else:
print('Sorry, no python.')
@Averroes
Averroes / example.py
Created April 10, 2015 14:13
unpack a fixed number of elements from iterables of arbitrary length
# example.py
#
# Unpacking of tagged tuples of varying sizes
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4),
]
@Averroes
Averroes / example.py
Created April 10, 2015 14:14
working with multiple mappings as a single mapping
# example.py
#
# Example of combining dicts into a chainmap
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
# (a) Simple example of combining
from collections import ChainMap
c = ChainMap(a,b)
@Averroes
Averroes / example.py
Created April 10, 2015 16:58
making separate directories import under a common namespace
import sys
sys.path.extend(['foo-package', 'bar-package'])
import spam.blah
import spam.grok