Created
December 31, 2016 18:20
-
-
Save decatur/f1172346450f79c41d4b8403b6a72100 to your computer and use it in GitHub Desktop.
Python Cheat Sheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Python Cheat Sheet | |
| # List Comprehension | |
| some_items = [{'index':i, 'value':i*i} for i in range(0,10)] | |
| filtered_items = [item for item in some_items if item['index']%2 == 1 ] | |
| # Dict Comprehension | |
| some_dict = {k: v for k, v in [('a', 1), ('b', 2)] if v % 2 == 0} | |
| # Set Comprehension | |
| some_set = {item for item in range(0,10)} | |
| # Generator Expression | |
| gen = ({'index':i, 'value':i*i} for i in range(0,10)) | |
| gen.next() | |
| for item in gen: print item | |
| # Generator Funcion | |
| def genGen(): | |
| for i in range(0,10): | |
| yield {'index':i, 'value':i*i} | |
| for item in genGen(): print item | |
| from itertools import islice | |
| list(islice(genGen(), 4, 7)) | |
| # Zipping | |
| [(1, 4), (2, 5), (3, 6)] == zip([1,2,3], [4,5,6]) | |
| # Spreads | |
| def foo(a, b): | |
| return a-b | |
| foo(*[2, 1]) == foo(**{'b':1, 'a':2}) | |
| # Subprocess Output Redirection | |
| # At first issue at the terminal prompt (see http://serverfault.com/questions/59262/bash-print-stderr-in-red-color) | |
| # color()(set -o pipefail;"$@" 2>&1>&3|sed $'s,.*,\e[31m&\e[m,'>&2)3>&1 | |
| # color python | |
| import subprocess,sys; | |
| # Red output | |
| sys.stderr.write('Hello\n') | |
| subprocess.call(["ls", "/404"]) | |
| # White output | |
| sys.stdout.write('Hello\n') | |
| subprocess.call(["ls", "/404"], stderr=sys.stdout.fileno()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment