x = ['a','b','c']for index, item inenumerate(x):print(index, item)
P:
array = [1,2,3,4,5]for i, e inenumerate(array,0):print i, e#0 1#1 2#2 3#3 4#4 5
NP:
for i inxrange(len(array)):print i, array[i]#0 1#1 2#2 3#3 4#4 5
import local module
# A.pydeffilter_items(items):for i in items:if i <10:yield i# B.pyfrom A import filter_items as A_filter_itemsdeffilter_items(items):for i in items:if i <=5:yield idefdo_something(items): x =A_filter_items(items) y =filter_items(items)return (x, y)
args & kwargs
defadd(one,two):return one + twomy_list = [1,2]x =add(*my_list)# x = 3my_dict ={"one":1,"two":2}y =add(**my_dict)#y = 3
itertools
>>>from itertools import zip_longest>>> x = [1,2,3,4]>>> y = ['a','b','c']>>>for i, j inzip_longest(x, y):... print(i, j)...1 a2 b3 c4None
one-line python code
>>> my_dict ={key: value for key, value inzip_longest(x,y)}>>> my_dict{1:'a',2:'b',3:'c',4:None}
slice
word =#some wordis_palindrome = word.find(word[-1::-1])
chain compare
P:
a =3b =11<= b <= a <10#True
NP:
a =3b =1b >=1and b <= a and a <10#True
boolean
P:
name ='Tim'langs = ['AS3','Lua','C']info ={'name':'Tim','sex':'Male','age':23}if name and langs and info:print('All True!')#All True!
NP:
if name !=''andlen(langs)>0and info !={}:print('All True!')#All True!
reverse
P:
defreverse_str( s ):return s[::-1]
NP:
defreverse_str( s ): t =''for x inxrange(len(s)-1,-1,-1): t += s[x]return t
join in list
P:
strList = ["Python","is","good"]res =' '.join(strList)#Python is good
NP:
res =''for s in strList: res += s +' '#Python is good#最后还有个多余空格
>>>int('10', 0)10>>>int('0x10', 0)16>>>int('010', 0)# does not work on Python 3.x8>>>int('0o10', 0)# Python >=2.6 and Python 3.x8>>>int('0b10', 0)# Python >=2.6 and Python 3.x2
in-place value swapping
>>> a =10>>> b =5>>> a, b(10,5)>>> a, b = b, a>>> a, b(5,10)
sum
from operator import addprintreduce(add, [1,2,3,4,5,6])
string
multi-line strings
>>> sql ="select * from some_table \where id > 10">>>print sqlselect *from some_table where id>10
or
>>> sql ="""select * from some_tablewhere id > 10""">>>print sqlselect *from some_table where id>10
or
>>> sql = ("select * from some_table "# <-- no comma, whitespace at end"where id > 10 ""order by name")>>>print sqlselect *from some_table where id>10 order by name
in
>>>'str'in'string'True>>>'no'in'yes'False>>>
Join
''.join(list_of_strings)
set
>>> a =set([1,2,3,4])>>> b =set([3,4,5,6])>>> a | b # Union{1,2,3,4,5,6}>>> a & b # Intersection{3,4}>>> a < b # SubsetFalse>>> a - b # Difference{1,2}>>> a ^ b # Symmetric Difference{1,2,5,6}
slice operators
a = [1,2,3,4,5]>>> a[::2]# iterate over the whole list in 2-increments[1,3,5]
>>>defg(n):... for i inrange(n):... yield i **2>>> t =g(5)>>> t.next()0>>> t.next()1>>> t.next()4>>> t.next()9>>> t.next()16>>> t.next()Traceback (most recent call last): File "<stdin>", line 1,in<module>StopIteration
or
deffab(max): a,b =0,1while a <max:yield a a, b = b, a+b>>>for i infab(20):... print i,",",...0,1,1,2,3,5,8,13,
or
>>> i = (1,2,3,4,5,6,7,8,9,10) # or any iterable object>>> iterators = [iter(i)] *2>>> iterators[0].next()1>>> iterators[1].next()2>>> iterators[0].next()3
$ pythonPython 2.5.1 (r251:54863, Jan 172008,19:35:17)[GCC 4.0.1 (Apple Inc. build 5465)] on darwinType "help","copyright","credits"or"license"for more information.>>> shared_var = "Set in main console">>>import code>>> ic = code.InteractiveConsole({ 'shared_var': shared_var })>>>try:... ic.interact("My custom console banner!")... exceptSystemExit, e:... print"Got SystemExit!"...My custom console banner!>>> shared_var'Set in main console'>>> shared_var = "Set in sub-console">>>import sys>>> sys.exit()Got SystemExit!>>> shared_var'Set in main console'
pretty print
>>>import pprint>>> stuff = sys.path[:]>>> stuff.insert(0, stuff)>>> pprint.pprint(stuff)[<Recursion on listwithid=869440>,'','/usr/local/lib/python1.5','/usr/local/lib/python1.5/test','/usr/local/lib/python1.5/sunos5','/usr/local/lib/python1.5/sharedmodules','/usr/local/lib/python1.5/tkinter']
or
from__future__import print_functionmylist = ['foo','bar','some other value',1,2,3,4]print(*mylist)
class & module
bash
python -c"import os; print(os.getcwd());"
assertion
>>>try:... assert []... exceptAssertionError:... print"This list should not be empty"This list should not be empty
import
try:import jsonexceptImportError:import simplejson as json
create new types
>>> NewType =type("NewType", (object,), {"x": "hello"})>>> n =NewType()>>> n.x"hello"
or
>>>classNewType(object):>>> x ="hello">>> n =NewType()>>> n.x"hello"
Manipulating sys.modules
>>>import sys>>>import hamTraceback (most recent call last): File "<stdin>", line 1,in<module>ImportError: No module named ham# Make the 'ham' module available -- as a non-module object even!>>> sys.modules['ham']='ham, eggs, saussages and spam.'>>>import ham>>> ham'ham, eggs, saussages and spam.'# Now remove it again.>>> sys.modules['ham']=None>>>import hamTraceback (most recent call last):
or
>>>import os# Stop future imports of 'os'.>>> sys.modules['os']=None>>>import osTraceback (most recent call last): File "<stdin>", line 1,in<module>ImportError: No module named os# Our old imported module is still available.>>> os<module 'os'from'/usr/lib/python2.5/os.pyc'>
Others
not hidden but still nice
import os.path as oproot_dir = op.abspath(op.join(op.dirname(__file__), ".."))
# Aligned with opening delimiter.foo =long_function_name(var_one, var_two, var_three, var_four)# More indentation included to distinguish this from the rest.deflong_function_name(var_one,var_two,var_three,var_four):print(var_one)# Hanging indents should add a level.foo =long_function_name( var_one, var_two, var_three, var_four)
no:
# Arguments on first line forbidden when not using vertical alignment.foo =long_function_name(var_one, var_two, var_three, var_four)# Further indentation required as indentation is not distinguishable.deflong_function_name(var_one,var_two,var_three,var_four):print(var_one)
optional
# Hanging indents *may* be indented to other than 4 spaces.foo =long_function_name( var_one, var_two, var_three, var_four)
if statemant
# No extra indentation.if (this_is_one_thing and that_is_another_thing):do_something()# Add a comment, which will provide some distinction in editors# supporting syntax highlighting.if (this_is_one_thing and that_is_another_thing):# Since both conditions are true, we can frobnicate.do_something()# Add some extra indentation on the conditional continuation line.if (this_is_one_thingand that_is_another_thing):do_something()o
income = (gross_wages+ taxable_interest+ (dividends - qualified_dividends)- ira_deduction- student_loan_interest)
imports
no:
import sys, os
yes:
import osimport sys
bad:
import<module>from*
absolute imports are recommended
import mypkg.siblingfrom mypkg import silbingfrom mypkg.sibling import example
explicit relative imports are acceptable
from.import siblingfrom.sibling import example
import a class from a class-containing module
from myclass import MyClassfrom foo.bar.yourclass import YourClass
local name classes
import myclassimport foo.bar.yourclass# use "myclass.MyClass" or "foo.bar.yourclass.YourClass"
module Level dunder names
Module level "dunder" names with two leading and two trailing underscores, such as __all__, __author__, __version__, etc
yes:
"""This is the example module.This module does stuff."""from__future__import barry_as_FLUFL__all__= ['a','b','c']__version__='0.1'__author__ ='Cardinal Biggles'import osimport sys