lang/py

Python Cheat Sheet

C/H 2014. 8. 1. 08:30

Python 구문 목록

출처 : List Of Syntax Used In Python!

PythonPython




Language Category: Object Oriented, Dynamically typed, Has anonymous functions
Various
indentationblock (grouping statements, especially when statements are not expressions)
\breaking lines (useful when end-of-line and/or indentation has a special meaning)
#commenting (until end of line)
< > <= >=comparison
min / maxcomparison (min / max (binary or more))
cmpcomparison (returns 3 values (i.e. inferior, equal or superior))
class X:
"""...
"""
def x():
"""...
"""
documentation comment
Err:510equality / inequality (deep)
Err:510equality / inequality (deep)
is / is notequality / inequality (shallow)
gc.collect()force garbage collection
( ... )grouping expressions
__file__information about the current line and file
evalruntime evaluation
execruntime evaluation
case-sensitivetokens (case-sensitivity (keywords, variable identifiers...))
[_a-zA-Z][_a-zA-Z0-9]*tokens (variable identifier regexp)
CamelCase for classes, underscores for methodstokens (what is the standard way for scrunching together multiple words)
=variable assignment or declaration (both)
global v1, v2variable assignment or declaration (declaration)
Functions
functools.partial(f, a)partial application (in the examples below, a normal call is "f(a,b)") (give the first argument)
lambda a, b: ...anonymous function
f(a,b,...)function call
f()function call (with no parameter)
__getattr__function called when a function is not defined (in dynamic languages)
def f(para1, para2, ...): ...function definition
returnfunction return value (breaks the control flow)
inspect.stack()[1]runtime inspecting the caller information
Control Flow
continue / breakbreaking control flow (continue / break)
returnbreaking control flow (returning a value)
try: a except exn: ...exception (catching)
finallyexception (cleanup: code executed before leaving)
raiseexception (throwing)
if c: ...if_then
b1 if c else b2if_then_else
if c: 
b1 
elif c2:
b2 
else: 
b3
if_then_else
for i in xrange(10, 0, -1)loop (for each value in a numeric range, 1 decrement)
for i in xrange(1, 11)loop (for each value in a numeric range, 1 increment (see also the entries about ranges))
for i in xrange(1, 11, 2)loop (for each value in a numeric range, free increment)
while c: ...loop (while condition do something)
;sequence
end-of-linesequence
Types
t(e)cast (computed conversion (calls an internal or a user-defined function))
n = tdeclaration
Object Oriented & Reflexivity
super(Class, self).meth(args)accessing parent method
classclass declaration
first parametercurrent instance
__class__get the type/class corresponding to an object/instance/value
hasattr(obj, "meth")has the method
class child(parent):inheritance
del, __del__manually call an object's destructor
object.method(para)method invocation
object.method()method invocation (with no parameter)
dirmethods available
copy.copy(o)object cloning
class_name(...)object creation
isinstancetesting class membership
Package, Module
automatically done based on the file namedeclare
__all__ = [ ... ]declare (selective export)
from p import *import (everything into current namespace)
import pimport (package (ie. load the package))
from p import name1, name2, ...import (selectively)
0package scope
Strings
s[n]accessing n-th character
chrascii to character
ordcharacter to ascii
str, `e`, reprconvert something to a string (see also string interpolation)
*duplicate n times
s[n:m+1]extract a substring
indexlocate a substring
findlocate a substring
rindexlocate a substring (starting at the end)
rfindlocate a substring (starting at the end)
'''...''', """..."""multi-line
pickle.dumpserialize (marshalling)
printsimple print (on any objects)
print e,simple print (on any objects)
%sprintf-like
0string concatenation
Err:510string equality & inequality
Err:510string equality & inequality
lenstring size
"\n"strings (end-of-line (without writing the real CR or LF character))
"... %(v)s ..." % vars()strings (with interpolation of variables)
'...'strings (with no interpolation of variables)
"..."strings (with no interpolation of variables)
'''...'''strings (with no interpolation of variables)
"""..."""strings (with no interpolation of variables)
strtype name
pickle.loadunserialize (un-marshalling)
upper / lowerupper / lower case character
upper / lower / capitalizeuppercase / lowercase / capitalized string
Booleans
Falsefalse value
Nonefalse value
0false value
""false value
()false value
[]false value
{}false value
notlogical not
or / andlogical or / and (short circuit)
Truetrue value
anything not falsetrue value
booltype name
Bags and Lists
zip(*l)2 lists from a list of couples
a.insert(i, e)adding an element at index (side-effect)
appendadding an element at the end (side-effect)
l[1:]all but the first element
reducef(... f(f(init, e1), e2) ..., en)
indexfind an element
for v in l: ...for each element do something
popget the last element and remove it
inis an element in the list
anyis the predicate true for an element
allis the predicate true for every element
enumerate(l)iterate with index
s.join(l)join a list of strings in a string using a glue string
filterkeep elements (matching)
[ x for x in l if p(x) ]keep elements (matching)
a[-1]last element
0list concatenation
[ a, b, c ]list constructor
ziplist of couples from 2 lists
listlist out of a bag
lenlist size
a[i]list/array indexing
setremove duplicates
reversereverse
reversedreverse
l[::-1]reverse
min / maxsmallest / biggest element
sortsort
sortedsort
maptransform a list (or bag) in another one
[ f(x) for x in l ]transform a list (or bag) in another one
maptransform two lists in parallel
listtype name
Various Data Types
a,computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (1-uple)
tuple([a])computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (1-uple)
()computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (empty tuple)
*tcomputable tuple (these are a kind of immutable lists playing a special role in parameter passing) (using a tuple for a function call)
h.get(k, returned_value_when_k_unfound)dictionary (access: read)
h[k]dictionary (access: read/write)
{ a: b, c: d }dictionary (constructor)
has_keydictionary (has the key ?)
k in hdictionary (has the key ?)
k not in hdictionary (has the key ?)
keysdictionary (list of keys)
valuesdictionary (list of values)
updatedictionary (merge)
del h[k]dictionary (remove by key)
dictdictionary (type name)
oroptional value (null coalescing)
Noneoptional value (null value)
voptional value (value)
rangerange (inclusive .. exclusive)
0record (selector)
a, b, ctuple constructor
tupletuple type
Mathematics
+ / - / * / /addition / subtraction / multiplication / division
& / | / ^bitwise operators (and / or / xor)
~bitwise operators (bitwise inversion)
<< / >>bitwise operators (left shift / right shift / unsigned right shift)
divmodeuclidian division (both quotient and modulo)
**exponentiation (power)
powexponentiation (power)
log10logarithm (base 10)
log(val, 2)logarithm (base 2)
loglogarithm (base e)
%modulo (modulo of -3 / 2 is 1)
-0negation
1000., 1E3numbers syntax (floating point)
07, 0xfnumbers syntax (integers in base 2, octal and hexadecimal)
1000numbers syntax (integers)
mathematicaloperator priorities and associativities (addition vs multiplication)
mathematicaloperator priorities and associativities (exponentiation vs negation (is -3^2 equal to 9 or -9))
randomrandom (random number)
random.seedrandom (seed the pseudo random generator)
sqrt / exp / abssquare root / e-exponential / absolute value
sin / cos / tantrigonometry (basic)
asin / acos / atantrigonometry (inverse)
int / round / floor / ceiltruncate / round / floor / ceil
float, decimal.Decimaltype name (floating point)
int, longtype name (integers)
Threads
OtherThread.join()Joining Another Thread (Suspending a thread until another thread completes)
class class_name(threading.Thread) {[override run method] }thread definition






반응형

'lang > py' 카테고리의 다른 글

Python Eclipse 개발 환경  (0) 2014.10.15
파이썬 프로그래밍 마스터를 위한 비디오 리소스 14!  (0) 2014.10.01
Must Have 파이썬 라이브러리  (0) 2014.08.06
파이썬 동영상 강좌  (0) 2014.07.21
python editplus 설정  (0) 2008.04.14