Cheat Sheet for Python: Life’s Pathetic, Let’s Pythonic!
Wenqiang Feng
E-mail: von198@gmail.com, Web: http://web.utk.edu/˜wfeng1; Wrapped from python3-in-one-pic, © Copyrights belong to the original author.
The Zen of Python Native Datatypes Flow Control
import this
The Zen of Python, by Tim Peters Boolean & None If
True; False # <class 'bool'> type(None) # <class 'NoneType'> import sys
Beautiful is better than ugly. if sys.version_info.major < 3:
Explicit is better than implicit. print('Version 2.X')
Simple is better than complex. elif sys.version_info.major > 3:
Complex is better than complicated. List
print('Future')
... l = ['python', 3, 'in', 'one'] print(type(l)) # <class 'list'> else:
print('Version 3.X')
Length: Index:
Syntax Roles
print(len(l)) # 4 print(l.index(3)) # 1
# Case-Seneitive Loop
a = 1; A = 2 Slicing: Alter:
print(a is not A) # True print(l[0]) l.pop() # 'one' For: While:
# Comments python ['python', 3, 'in'] # h prod = 1; i =1
# Comments will be ignored # Comments will be ignored print(l[-1]) print(l.pop(1)) # 'one' for i in 'hello': # e while i< 4:
# 4 spaces identation one 3 print(i) # l prod *= i
# Code blocks are defined by print(l[1:-1]) print(l.remove('in')) # None # l i += 1
# their indentation [3, 'in'] ['python'] # o print(prod) # 6
print(l[::-1]) l.append('pic') # None
['one', 'in', 3, 'python'] ['python', 'pic'] Break/continue: Iterations & Generators:
Native Datatypes print(l[::2]) l.extend(['!','!']) # None python = iter('python')
['python', 'in'] ['python', 'pic', '!', '!'] <str_iterator object at ****>
Number print(l[:-2:1]) l.insert(2,4) # None for n in range(2, 10): for i in python:
['python', 3] ['python', 'pic', 4, '!', '!'] if n % 2 ==0: print(i)
Integer: Float:
print('even number',n) def reverse(d):
a = 1 c = 1.2 # 1.2 ix=range(len(d)-1,-1,-1)# n
continue
b = 0x10 # 16 d = .5 # 0.5 Tuple for i in ix: # o
if n > 5:
print(b) # 16 g = 3.14e-2 # 0.0314 yield d[i] # h
print('GT 5')
print(type(b)) # <class 'int'> print(type(g)) #<class 'float'> tp=(1,2,3,[4,5])#Immutable list print(type(l)) #<class 'tuple'> nohtyp = reverse('python') # t
break
Complex: Operators: Length & slicing & update: Assign multiple value: for i in nohtyp: # y
print(i) # p
e = 1+2j # (1+2j) print(1+1) # 2 print(2**2)# 4 print(len(tp)) # 4 v = (3,2,'a')
f = complex(1,2) # (1+2j) print(2-2) # 0 print(9//4)# 2 print(tp[2]) # 3 (c,b,a) = v
print(type(e))#<class'complex'> print(3*3) # 9 print(9%4) # 1 print(tp[:3]) # (1,2,3) print(a,b,c) # a 2 3 Comprehension
print(f == e) # True print(5/4) # 1.25 tp[3][1] = 6 # (1,2,3,[4,6]) tp = (1,) # Not tp=(1)
List
Casting:
[2*x for x in range(4) if x**2>3] # with filter [4, 6]
# Integer/String -> Float # Float/String -> Integer Set [4*x if x<2 else x for x in range(4)] # w/o filter [0, 4, 2, 3]
print(float(3)) # 3.0 int(3.14) # 3 [(x,y) for x in range(2) for y in range(2)]
print(3/1) # 3.0 int('100', base = 10) # 100 st={'s','e','T'} print(type(st)) #<class 'set'>
# [(0, 0), (0, 1), (1, 0), (1, 1)]
print(float("3.14"))# 3.14 int('1010', base = 2) # 10 Length: Empty: # matix transposed
Unordered, collections, unique st = set() matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
print(len(st)) # 3 st.clear() [[row[i] for row in matrix] for i in range(4)]
String # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Alter [val for row in matrix for val in row ]
s1 = ':dog:\n Dogge' print(type(s1)) #<class 'str'>
st.add('t') # {'e','T','t','s'} st.pop() # {'!','s','T','t'} # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
s2 = "Dogge's home" print('%s, %s, %s'%(s1,s2,s3))
s3 = """ :dog: st.add('t') # {'e','T','t','s'} st.discard('t') # {'!','s','T'} Set
Hello, Dogge, Dogge's home, st.update(['!','!']) st.remove('T') # {'!', 's'}
# {'e', '!', 's', 'T', 't'} {2*x for x in range(4) if x**2>3} # with filter {4, 6}
Dogge! Hello, st.clear() # set()
{4*x if x<2 else x for x in range(4)} # w/o filter {0, 2, 3, 4}
""" Dogge!
set([(x,y) for x in range(2) for y in range(2)])
Length & operator: Slicing: Dict # {(0, 1), (1, 0), (0, 0), (1, 1)}
print(len(s1)) # 12 print('{0}:{1}' # Dogge:home Dict
print('ab'+'.'+'xy') # ab.xy dic = {'k1': 1, 'k2': 2} print(type(dic))#<class 'dict'>
.format(s2[:5],s2[-4:]))
ls = {s:len(s) for s in ['Python','Javascript','r']}
Casting Length & check: get & update: {'Python': 6, 'Javascript': 10, 'r': 1}
print(len(dic)) # 2 print(dic['k1']) # 1 sl = {v: k for k, v in ls.items()}
print(str(3.14)) # 3.14 print(str({1,2,3})) # {1,2,3}
print(dic.keys()) # ['k1','k2'] print(dic.get('k1')) # 1 {6: 'Python', 10: 'Javascript', 1: 'r'}
print(str(3)) # 3 print(str({'python':'py',
print(dic.values())# [1,2] dic['k2']= 3 #{'k1':1,'k2':3} mapping = {'Python':'C','Javascript':'C++'}
print(str([1,2,3])) # [1,2,3] 'java':'js'}))
print('k2' in dic) # True dic['k3']= 3 {mapping.get(col,col):ls[col] for col in ls}
print(str((1,2,3))) # (1,2,3) {'python':'*.py','java':'*.js'}
print('v1' in dic) # False # {'k1':1, 'k2':3, 'k3': 3} {'C': 6, 'C++': 10, 'r': 1}
©All Rights Reserved by Dr.Wenqiang Feng. Powered by LATEX. Updated:04-07-2019. von198@gmail.com
Function Class (Object-oriented programming) Module
Definition Class Import
def func(): class Animal: import os
""" def fly(_): from sys import version_info as PY_VERSION
return 'Hello World!' print('I can fly') print('version .'.format(PY_VERSION.major,PY_VERSION.minor))
""" # version 3.7
return 'Hello World!' a = Animal() from math import pi
print(func()) Hello World! a.fly() # I can fly print(pi) # 3.141592653589793
print(func.__doc__) return 'Hello World!' print(a.__doc__) # This is an Animal.
Path
Default arguments init & self
%%script bash
def func(name = 'George'): class Animal: pwd # /home/feng/Dropbox/MyPython/
""" def __init__(self, can_fly =False): echo $PYTHONPATH
return 'Hello World, name!' self.can_fly = can_fly /opt/spark/python:/opt/spark/python/lib/py4j-0.10.4-src.zip:
:param name: the name of the user. default: George def fly(self): # python
:return: 'Hello World, name!' if self.can_fly: import sys, os
""" print('I can fly') os.path.abspath(' ') # '/home/feng/Dropbox/MyPython/'
return 'Hello World, {name}!'.format(name=name) else:
print(func()) Hello World, George! print('I can not fly')
Package
a = Animal() # callin g__init__() when instaniation!
Keyword arguments a.fly() # I can not fly MyModule
|-- SubModuleOne
def func(v, l = 'Python'): b = Animal(can_fly=True) # callin g__init__() when instaniation! |-- __init__.py
""" b.fly() # I can fly |-- smo.py
return 'version, name!' # smo.py
""" def run():
return '{v}, {l}!'.format(v=v, l=l) Instance print("Running MyModule.SubModuleOne.smo!")
print(func(3.6)) 3.6, Python!
print(func(3.6,'r')) 3.6, r! class Animal: from MyModule.SubModuleOne import smo
pass smo.run() # Running MyModule.SubModuleOne.smo!
class Human:
Arbitrary arguments pass
def func(*args, con=" & "): a = Animal() Pythonic
print(isinstance(args, tuple)) h = Human()
Reverse a[::-1]
print('Hello', con.join(args)) print(isinstance(a, Animal)) # True
func('Python','C', 'C++') Hello Python & C & C++ print(isinstance(h,Animal)) # False Check [s in J for s in S] # J = 'aA', S = 'aAAbbb'
Complex sum tuple(map(sum, zip(a,b))) # a = (1,0), b = (-1, 0)
Lambda Inheritance
Transpose [[row[i] for row in M] for i in range(len(M[1]))]
pairs = [(1,'one'),(2,'two'),(3,'three'),(4,'four')] class Animal:
def __init__(self, can_fly=False): Flat list [val for row in matrix for val in row ]
pairs.sort(key=lambda pair: pair[1]) self.can_fly = can_fly
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] def fly(self): Exchange a, b = b, a
pairs.sort(key=lambda pair: pair[0],reverse=True) if self.can_fly:
With filter [2*x for x in range(4) if x**2>3]
[(4, 'four'), (3, 'three'), (2, 'two'), (1, 'one')] print('I can fly')
else: w/o filter [4*x if x<2 else x for x in range(4) ]
print('I can not fly')
Decorator dict get value = D.get(key, 0) # better than D[key]
class Dog(Animal):
def log(f): def bark(self): with open('filename.txt') as f:
def wrapper(): print('woof') open file for line in f:
print('Hey log˜') d = Dog() print(line)
f() d.fly() # I can not fly
print('Bye log!') d.bark() # woof string join ''.join(letters)
return wrapper
for i, elem in enumerate(lst):
traverse indx print(i,elem)
@log Override
def fa():
print('This is fa!') class Bird(Animal): for x, y in zip(a,b):
zip
""" print(x,y)
# Equal to ... This is a Dog.
def fb(): """ Dict traverse {v: k for k, v in D.items()}
print('This is fb!') def fly(self):
Counter Counter(s) # from collections import Counter
print("I'm flying high!")
print(fa()) Hey log˜ This is fa! Bye log! None b = Bird() sorted sorted(d.items(), key=lambda t: t[1],reverse =True)
fb = log(fb) Hey log˜This is fb! Bye log! None b.fly() # I'm flying high!
© All Rights Reserved by Dr.Wenqiang Feng. Powered by LATEX. Updated:04-07-2019. von198@gmail.com