x = ['a', 'b', 'c']
for index, item in enumerate(x):
print(index, item)
P:
array = [1, 2, 3, 4, 5]
for i, e in enumerate(array,0):
print i, e
#0 1
#1 2
#2 3
#3 4
#4 5
NP:
for i in xrange(len(array)):
print i, array[i]
#0 1
#1 2
#2 3
#3 4
#4 5
import local module
# A.py
def filter_items(items):
for i in items:
if i < 10:
yield i
# B.py
from A import filter_items as A_filter_items
def filter_items(items):
for i in items:
if i <= 5:
yield i
def do_something(items):
x = A_filter_items(items)
y = filter_items(items)
return (x, y)
args & kwargs
def add(one, two):
return one + two
my_list = [1, 2]
x = add(*my_list) # x = 3
my_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 in zip_longest(x, y):
... print(i, j)
...
1 a
2 b
3 c
4 None
one-line python code
>>> my_dict = {key: value for key, value in zip_longest(x,y)}
>>> my_dict
{1: 'a', 2: 'b', 3: 'c', 4: None}
slice
word = #some word
is_palindrome = word.find(word[-1::-1])
chain compare
P:
a = 3
b = 1
1 <= b <= a < 10 #True
NP:
a = 3
b = 1
b >= 1 and 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 != '' and len(langs) > 0 and info != {}:
print('All True!') #All True!
reverse
P:
def reverse_str( s ):
return s[::-1]
NP:
def reverse_str( s ):
t = ''
for x in xrange(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
#最后还有个多余空格
sum = 0
maxNum = -float('inf')
minNum = float('inf')
prod = 1
for num in numList:
if num > maxNum:
maxNum = num
if num < minNum:
minNum = num
sum += num
prod *= num
# sum = 15 maxNum = 5 minNum = 1 prod = 120
list comprehensions
P:
l = [x*x for x in range(10) if x % 3 == 0]
# l = [0, 9, 36, 81]
NP:
l = []
for x in range(10):
if x % 3 == 0:
l.append(x*x)
# l = [0, 9, 36, 81]
>>> int('10', 0)
10
>>> int('0x10', 0)
16
>>> int('010', 0) # does not work on Python 3.x
8
>>> int('0o10', 0) # Python >=2.6 and Python 3.x
8
>>> int('0b10', 0) # Python >=2.6 and Python 3.x
2
in-place value swapping
>>> a = 10
>>> b = 5
>>> a, b
(10, 5)
>>> a, b = b, a
>>> a, b
(5, 10)
sum
from operator import add
print reduce(add, [1,2,3,4,5,6])
string
multi-line strings
>>> sql = "select * from some_table \
where id > 10"
>>> print sql
select * from some_table where id > 10
or
>>> sql = """select * from some_table
where id > 10"""
>>> print sql
select * from some_table where id > 10
or
>>> sql = ("select * from some_table " # <-- no comma, whitespace at end
"where id > 10 "
"order by name")
>>> print sql
select * 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 # Subset
False
>>> 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]
or
>>> a[::-1]
[5,4,3,2,1]
or
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:5] = [42]
>>> a
[42, 5, 6, 7, 8, 9]
>>> a[:1] = range(5)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[::2]
>>> a
[1, 3, 5, 7, 9]
>>> a[::2] = a[::-2]
>>> a
[9, 3, 5, 7, 1]
>>> class NewType(object):
>>> x = "hello"
>>> n = NewType()
>>> n.x
"hello"
Manipulating sys.modules
>>> import sys
>>> import ham
Traceback (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 ham
Traceback (most recent call last):
or
>>> import os
# Stop future imports of 'os'.
>>> sys.modules['os'] = None
>>> import os
Traceback (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 op
root_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.
def long_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.
def long_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_thing
and that_is_another_thing):
do_something()o
import mypkg.sibling
from mypkg import silbing
from mypkg.sibling import example
explicit relative imports are acceptable
from . import sibling
from .sibling import example
import a class from a class-containing module
from myclass import MyClass
from foo.bar.yourclass import YourClass
local name classes
import myclass
import 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 os
import sys