Skip to content

Instantly share code, notes, and snippets.

@nad2000
Last active December 25, 2015 03:49
Show Gist options
  • Save nad2000/6912310 to your computer and use it in GitHub Desktop.
Save nad2000/6912310 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# Original from:
# http://pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-python
colors = ['red', 'green', 'blue', 'yellow']
names = ['apple', 'carrot', 'melon']
for color in reversed(colors):
print color
for i, color in enumerate(colors):
print i, '-->', color
# originally zip was introduced in Lisp:
# izip - an iterator implementation of zip
from itertools import izip
for name, color in izip(names, colors):
print name, '-->', color
for color in sorted(colors):
print color
for color in sorted(colors, reverse=True):
print color
# custom sort:
for color in sorted(colors, key=len): # sorted(colors, cmp=FUNCTION)
print color
## Call a function until a sentinel value:
#blocks = []
#from functools import partial
#for block in iter(partial(f.read, 32), ''):
# blocks.append(block)
d = dict(izip(names, colors) )
for k in d:
print k
# del d[k] ### NB! cannot mutate the dictionary
# if you need to mutated the dictionary:
for k in d.keys():
if k.startswith('a'):
del d[k]
for k in d:
print k, '-->', d[k] # not good because it needs to re-hash keys
# better:
print '# W/O re-shash:'
for k, v in d.items():
print k, '-->', v
# for larger dictionaries:
print '# W/O re-shash using iteritems():'
for k, v in d.iteritems():
print k, '-->', v
# defaultdict:
print '# defaultdict:'
from collections import defaultdict
d = defaultdict(int)
for color in colors:
d[color] += 1
print d
# Grouping:
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
print '# Grouping:'
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
print d
print '# Grouping with setdefault:'
d = {}
for name in names:
key = len(name)
d.setdefault(key, []).append(name)
print d
print '# Grouping with defaultdict:'
d = defaultdict(list)
for name in names:
d[len(name)].append(name)
print d
print '# Popitem:'
while d:
k,v = d.popitem()
print k, '-->', v
print d
## Linking dicti
import os
from argparse import ArgumentParser
defaults = {'color':'red', 'user': 'guest'}
parser = ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args([])
command_line_args = {k:v for k, v in
vars(namespace).items() if v}
d = defaults.copy()
d.update(os.environ)
d.update(command_line_args)
print d
#print '# with ChainMap:'
# requires Python 3.x
#d = ChainMap(command_line_args, os.environ, defaults)
# Named tuples:
print '# Named tuples:'
from collections import namedtuple
TestResult = namedtuple('TestResult', ['failed', 'attempted'])
print TestResult( 1, 4)
# Unpacking sequences:
fname, lname, age, email = 'Raymond', 'Hettinger', 0x30, '[email protected]'
print (fname, lname, age, email)
def fibonacci(n):
x, y = 0, 1
for i in xrange(n):
print x
# NB! simmultanious update (no need for a temporal variable)
# it eliminats an entire class of errors due to out-of-order updates
x, y = y, x+y
fibonacci(10)
# decorator application:
# Using decorators to factor-out administrative logic, eg,
# web handler - appliction logic; caching - addministrative logic
# use @cache(...)
# with: (Python 3.x)
#from contextlib import ignored
#with ignored(OSError):
# os.remove('somefile.tmp')
# With pre-Python 3.x
from contextlib import contextmanager
@contextmanager
def ignored(*exceptions):
try:
yield
except exceptions:
pass
# Factor-out temporary context:
with ignored(OSError):
os.remove('somefile.tmp')
import sys
from contextlib import contextmanager
@contextmanager
def redirect_stdout(fileobj):
oldstdout = sys.stdout
sys.stdout = fileobj
try:
yield fileobj
finally:
sys.stdout = oldstdout
with open('help.txt','w') as f:
with redirect_stdout(f):
help(pow)
print >> sys.stderr, '*** Saved to', f.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment