1.在交互模式下,特殊变量“_”表示上一条命令的执行结果(注:类似于shell下的$?)。该变量只在交互模式下生效,其他情况下无效。
2.一种更优雅的print方式:
print '%3d %0.2f' %(year, principal) =>
print format(year, '3d'), format(principal, '0.2f')
3.strings也有一个类似的format方法
print '%3d %0.2f' %(year, principal) =>
print '{0:3d}{1:0.2f}'.format(year, principal)
4.pass关键字可以创建一个空语句
if a < b:
pass
else:
print 'Computer says No'
5.使用and/or/not关键字来创建复合表达式
if product == 'game' and type == 'pirate memory' and not (age < 4 or age > 8):
print 'I will take it'
6.python没有case关键字,可以使用elif来实现case的功能
if suffix == ".htm":
content = "text/html"
elif suffix == ".jpg":
content = "image/jpeg"
elif suffix == ".png":
content = "image/png"
else:
raise RuntimeError("Unknown content type")
7.raise产生一个异常,类似于throw
8.使用True和False来表示布尔值
if 'spam' in s:
has_spam = True
else:
has_spam = False
9.in操作符也产生布尔值
has_spam = 'spam' in s;
10.open函数打开一个文件,返回一个文件对象
f = open("foo.txt") # Returns a file object
line = f.readline() # Invokes readline() method on file
while line:
print line, # trailing ',' omits newline character
# print(line,end='') # Use in Python 3
line = f.readline()
f.close()
11.对于集合中元素的遍历,如输入行,数字,字符串集合,python提供for语句来遍历该迭代器,上例可写成:
for line in open('foo.txt')
print line
12.print函数接受一个文件对象参数,来对输出进行重定向
print >> f,"%3d %0.2f" %(year,principal)
python3中格式如下:
print("%3d %0.2f" % (year,principal),file=f)
13.函数对象支持write方法来写入数据,
f.write('%3d %0.2f' %(year, principal))
14.sys模块提供了标准输入/标准输出/标准出错
import sys
sys.stdout.write('Enter your name: ')
sys.stdin.readline()
15.raw_input([prompt])函数也可以实现从标准输入读取数据
name = raw_input('Enter your name: ')
python3中该函数改为input
16.字符串:单引号与双引号作用一样,三引号可以创建跨行字符串。字符串被存储为字符序列,可以通过下标来访问指定位置的字符,下标从0开始
a = 'Hello World'
b = a[4] # b = 'o'
17.字符串分片:s[i:j]
c = a[:5] # c = "Hello"
d = a[6:] # d = "World"
e = a[3:8] # e = "lo Wo"
18.字符串使用+操作符来拼接:
g = a + " This is a test"
19.字符串的+操作符只用于字符串拼接,如果要实现类似整数的+,要先将字符串转化为整数:
x = "37"
y = "42"
z = x + y # z = "3742" (String Concatenation)
z = int(x) + int(y) # z = 79 (Integer +)
20.将其他值转换为字符串的方式:str, repr, format
s = 'The values of x is ' + str(x) #construct a str object using x
s = 'The values of x is ' + repr(x) #Return the canonical string representation of the object
s = 'The values of x is ' + format(x, '3d') #format
str与repr的区别在于:str返回x的print值,而repr返回x在内存中的精确标示,这对双精度数会有不同:
x = 3.4
str(x) => '3.4'
repr(x) => '3.39999999999999999999999999999999'
21.list为任意对象的一个序列,以方括号包围:
names = [ "Dave", "Mark", "Ann", "Phil" ]
通过下标来访问list元素,从0开始:
a = names[2] # Returns the third item of the list, "Ann"
names[0] = "Jeff" # Changes the first item to "Jeff"
22.list追加使用append方法:
names.append("Paula")
23.list插入使用insert方法:
names.insert(2, "Thomas")
24.list切片,类似于字符串的分片
b = names[0:2] # Returns [ "Jeff", "Mark" ]
c = names[2:] # Returns [ "Thomas", "Ann", "Phil", "Paula" ]
names[1] = 'Jeff' # Replace the 2nd item in names with 'Jeff'
names[0:2] = ['Dave','Mark','Jeff'] # Replace the first two items of
# the list with the list on the right.
25.使用+操作符来拼接list
a = [1,2,3] + [4,5] # Result is [1,2,3,4,5]
26.创建空list
names = [] # An empty list
names = list() # An empty list
27.list可以包含任意元素,也可以嵌套list
a = [1,"Dave",3.14, ["Mark", 7, 9, [100,101]], 10]
28.嵌套list的元素通过多重下标来获取
a[1] # Returns "Dave"
a[3][2] # Returns 9
a[3][3][1] # Returns 101
29.list comprehension:
fvalues = [float(line) for line in open(sys.argv[1])]
30.求最大值与最小值:
min(fvalues)
max(fvalues)
31.tuple元组是一系列数据的集合,以小括号包围:
stock = ('GOOG', 100, 490.10)
address = ('www.python.org', 80)
person = (first_name, last_name, phone)
32.没有小括号时,python也能识别出一个元组:
stock = 'GOOG', 100, 490.10
address = 'www.python.org',80
person = first_name, last_name, phone
33.0个元素与1个元素元组的定义方式:
a = () # 0-tuple (empty tuple)
b = (item,) # 1-tuple (note the trailing comma)
c = item, # 1-tuple (note the trailing comma)
34.可以通过数字下标的方式来获取元组的元素,也可以通过如下方式来分解元组
name, shares, price = stock
host, port = address
first_name, last_name, phone = person
35.元组支持像list的大多数操作,如下标,分片,拼接,但元组的内容一旦创建后就不能在修改,即不能修改元素,删除元素,追加元素。
36.list又是会预分配一部分内存,来优化像添加元素这种操作;而由于元组是不可修改的,因此元组使用更加紧凑的方式来存储,没有额外的内存。
37.string.split()函数用于分割字符串,返回一个list
38.集合set是一系列对象的无序集合,通过set()来创建一个集合
s = set([3,5,9,10]) # Create a set of numbers
t = set("Hello") # Create a set of unique characters
39.与list和tuple不同,set中的元素是无序的,因此不能通过下标来访问。并且,set中的元素是唯一不重复的,类似于C++中的set
40.set支持标准的集合操作,如交,差,并,异差
a = t | s # Union of t and s
b = t & s # Intersection of t and s
c = t – s # Set difference (items in t, but not in s)
d = t ^ s # Symmetric difference (items in t or s, but not both)
41.使用add/update来更新set中的元素,使用remove来删除set中的元素
t.add('x') # Add a single item
s.update([10,37,42]) # Adds multiple items to s
42.字典dictionary类似于关联数组或哈希表,通过键来访问值。字典通过大括号包围
stock = {
"name" : "GOOG",
"shares" : 100,
"price" : 490.10
}
通过键作为下标来访问其对应的值:
name = stock["name"]
value = stock["shares"] * shares["price"]
插入和修改也通过键下标来操作
stock["shares"] = 75
stock["date"] = "June 7, 2007"
43.list和dictionary不能作为dictionary的下标,因为他们的内容会改变,而元组可以
44.创建空字典
prices = {} # An empty dict
prices = dict() # An empty dict
45.使用in操作符来测试一个键是否存在于字典中
if 'scox' in prices:
p = prices['scox']
else:
p = 0
46.字典的get方法可以获取某个键对应的值,并提供一个默认值
p = prices.get('scox', 0)
47.使用字典的键创建一个list
syms = list(prices) # syms = ["AAPL", "MSFT", "IBM", "GOOG"]
48.使用del来删除字典的一个键值对
del prices["MSFT"]
49.range( i , j [, stride ])函数创建一个序列,值从i到j-1,stride为增量。如果开始值i省略,则默认为0.如果stride省略,则默认为1
a = range(5) # a = 0,1,2,3,4
b = range(1,8) # b = 1,2,3,4,5,6,7
c = range(0,14,3) # c = 0,3,6,9,12
d = range(8,1,-1) # d = 8,7,6,5,4,3,2
50.python2中range创建非常大的序列时,很耗内存,此时可以使用xrange来代替。python3中xrange即为range,旧range的这种行为已经消除。
51.for循环可以遍历各种对象的序列,如字符串,list,字典,文件
a = "Hello World"
# Print out the individual characters in a
for c in a:
print c
b = ["Dave","Mark","Ann","Phil"]
# Print out the members of a list
for name in b:
print name
c = { 'GOOG' : 490.10, 'IBM' : 91.50, 'AAPL' : 123.15 }
# Print out all of the members of a dictionary
for key in c:
print key, c[key]
# Print all of the lines in a file
f = open("foo.txt")
for line in f:
print line,
52.使用def来定义函数,return返回函数值
def remainder(a,b):
q = a // b # // is truncating division.
r = a - q*b
return r
53.可以使用元组来返回多个值
def divide(a, b):
q = a //b
r = a - q * b
return (q, r)
然后通过如下方式来分解元组
quotient, remainder = divide(1456,33)
54.函数形参可以有默认值
def connect(hostname, port, timeout = 3000):
# function body
调用时可以忽略默认参数
connect('www.python.org', 80)
55.可以通过关键参数以任意顺序来为函数形参赋值
connect(port=80,hostname="www.python.org")
56.函数内部定义的变量为局部变量,作用域为local。如果在函数内部使用全局变量,使用global关键字
count = 0
...
def foo():
global count
count += 1 # Changes the global variable count
57.使用yield语句来实现一个生成器generator,类似于C/C++的static,如fibonacci数列的实现
def fibonacci():
first = 0
second = 1
yield first
while 1:
yield second
first, second = second, first + second
58.yield可以用于创建协程coroutine。
def print_matches(matchtext):
print 'Looking for ', matchtext
while True:
line = (yield)
if matchtext in line:
print line
>>> matcher = print_matches("python")
>>> matcher.next() # Advance to the first (yield)
Looking for python
>>> matcher.send("Hello World")
>>> matcher.send("python is cool")
python is cool
>>> matcher.send("yow!")
>>> matcher.close() # Done with the matcher function call
>>>
59.dir()函数可以列出对象的所有可执行方法及全局变量
60.对象内的下划线方法定义了给类型的操作符,如__add__()方法实现了+操作符
61.class关键字用于定义一种新的数据类型
class Stack(object):
def __init__(self):
self.stack = [] # Initialize the stack
def push(self, object):
self.stack.append(object)
def pop(self):
return self.stack.pop()
def length(self):
return len(self.stack)
62.class定义类型中,小括号表示继承,即Stack继承object。object是所有python对象的根对象。所有函数的第一个成员都表示该对象自身,即C++中的this。默认情况下使用self。
63.@staticmethod修饰符可以指示创建静态方法
class EventHandler(handler):
@staticmethod
def dispatcherThread():
# wait for request
EventHandler.dispatcherThread() # call method like a function
64.使用try/except来捕获异常
try:
f = open('file.txt', 'r')
except IOError as e:
print e
65.使用raise来抛出一个异常
raise RuntimeError('Computer says no')
66.使用with语句来管理系统资源,如锁,文件,网络连接等
import threading
message_lock = threading.lock
......
with message_lock:
message.add(newmessage)
当进入with语句块时,锁会自动获取;当离开语句块时,锁会自动释放。
67.使用import...as...对倒入的模块重命名
import div as foo
a, b = foo.divide(2305, 29)
68.加载模块的内容到当前的命名空间,使用from ... import ...
from div import divide
a, b = divide(2305, 29)
加载模块的所有内容,使用
from div import *
69.使用help()来查看某一个模块的帮助
70.使用pydoc命令来查看摸个模块的doc文档
71.块缩进的数量没有限制,但同一块代码的缩进必须相同
72.尽量不要用tab来做缩进
73.以-t选项运行python时,对于tab与空格混用的情况,python会产生一个warning;以-tt选项允许python时,python会产生TabError
74.同一行的多个语句,需要以分号分割
75.标识符职能包括字符,数字,下划线,且只能以字符或下划线开头
76.标识符大小写敏感
77.python保留字:
and del from nonlocal try
as elif global not while
assert else if or with
break except import pass yield
class exec in print
continue finally is raise
def for lambda return
78.以单下划线开头的标识符如_foo,在使用from ... import *时,不会被导入;前后双下划线标识符如__init__保留用作特殊方法;双下划线开头的标识符如__bar用于标识类的私有方法
79.四种内置整数类型
Boolean:True False
Integer
Floating-point number
Comples number
80.二进制整数以0b开头;八进制整数以0开头;十六进制整数以0x开头
81.模块,类,方法定义时的第一句话如果是一条字符串,该字符串就是该对象的doc
def fact(n):
''' This function computes a factorial '''
if n <= 1:
return 1
else:
return n * fact(n - 1)
82.修饰符可以用于修饰函数,方法,或类定义
83.在文档的第一或第二行使用编码注释来制定文档的编码方式
#!/usr/bin/python
# -*- coding: UTF-8 -*-
s = "Jalape?o" # String in quotes is directly encoded in UTF-8.
84.对象的标识可以看成对象在内存中的位置指针
85.内置函数id()返回对象的identity整数值;该整数值通常对应于该对象在内存中的位置;
86.is 操作符用于比较两个变量是否指向同一个对象
87.内置函数type()返回对象的类型
# Compare two objects
def compare(a,b):
if a is b:
# a and b are the same object
statements
if a == b:
# a and b have the same value
statements
if type(a) is type(b):
# a and b have the same type
statements
88.内置函数isinstance(object, type)判断对象是否是某一个类型
if isinstance(s, list):
s.append(item)
if isinstance(d, dict):
d.update(t)
89.python中所有对象采用引用计数;sys.getrefcount(object)函数可以查看对象的引用计数。当计数值为0时,该对象可以被gc回收
90.对于不可变对象如数字,字符串,元组,赋值操作创建对象的一份拷贝;对于可变对象如list,字典,仅仅是创建一个指向对象的引用
>>> a = [1,2,3,4]
>>> b = a # b is a reference to a
>>> b is a
True
>>> b[2] = -100 # Change an element in b
>>> a # Notice how a also changed
[1, 2, -100, 4]
>>>
91.容器对象的浅拷贝与深拷贝:浅拷贝只创建一个对象,对象内部的元素是指向原对象内部元素的引用
>>> a = [ 1, 2, [3,4] ]
>>> b = list(a) # Create a shallow copy of a.
>>> b is a
False
>>> b.append(100) # Append element to b.
>>> b
[1, 2, [3, 4], 100]
>>> a # Notice that a is unchanged
[1, 2, [3, 4]]
>>> b[2][0] = -100 # Modify an element inside b
>>> b
[1, 2, [-100, 4], 100]
>>> a # Notice the change inside a
[1, 2, [-100, 4]]
>>>
深拷贝创建一个对象,并递归式拷贝其内部的所有对象
>>> import copy
>>> a = [1, 2, [3, 4]]
>>> b = copy.deepcopy(a)
>>> b[2][0] = -100
>>> b
[1, 2, [-100, 4]]
>>> a # Notice that a is unchanged
[1, 2, [3, 4]]
>>>
92.通过copy模块的deepcopy方法来实现深拷贝
93.python内置类型
Type Category Type Name Description
None type(None) The null object None
Numbers int Integer
long Arbitrary-precision integer (Python 2 only)
float Floating point
complex Complex number
bool Boolean ( True or False )
Sequences str Character string
unicode Unicode character string (Python 2 only)
list List
tuple Tuple
xrange A range of integers created by xrange() (In Python 3, it is called range. )
Mapping dict Dictionary
Sets set Mutable set
frozenset Immutable set
94.序列类型的通用操作
Item Description
s [ i ] Returns element i of a sequence
s [ i : j ] Returns a slice
s [ i : j:stride ] Returns an extended slice
len( s ) Number of elements in s
min( s ) Minimum value in s
max( s ) Maximum value in s
sum( s [, initial ]) Sum of items in s
all(s) Checks whether all items in s are True .
any(s) Checks whether any item in s is True
s [ i ] = v Item assignment
s [ i : j ] = t Slice assignment
s [ i : j:stride ] = t Extended slice assignment
del s [ i ] Item deletion
del s [ i : j ] Slice deletion
del s [ i : j:stride ] Extended slice deletion
95.list操作
Method Description
list( s ) Converts s to a list.
s .append( x ) Appends a new element, x , to the end of s .
s .extend( t ) Appends a new list, t , to the end of s .
s .count( x ) Counts occurrences of x in s
s .index( x [, start [, stop ]]) Returns the smallest i where s [ i ]== x . start and stop optionally specify the starting
and ending index for the search. a ValueError exception is raised if not found
s .insert( i,x ) Inserts x at index i .
s .pop([ i ]) Returns the element i and removes it from the list. If i is omitted, the last element is
returned. Raises IndexError if list is empty or index is out of range.
s .remove( x ) Searches for x and removes it from s . a ValueError exception is raised if not found
s .reverse() Reverses items of s in place. return none
s .sort([ key [, reverse ]]) Sorts items of s in place. key is a key function. reverse is a flag that sorts the list in
reverse order. key and reverse should always be specified as keyword arguments. return none
96.函数
abs( x ) Absolute value
divmod( x , y ) Returns (x // y, x % y )
pow( x , y [, modulo ]) Returns ( x ** y ) % modulo
round( x ,[ n ]) Rounds to the nearest multiple of 10 -n (floating-point numbers only)
97.enumerate(sequence)函数用于产生序列的元组,如(0, s [0]) ,(1, s [1]) , (2, s [2])等等
98.try/except/else/finally
try:
f = open('file.txt')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else: #This code is executed if the code in the try block doesn’t raise an exception.
data = f.read()
finally: #This code is executed regardless of whether an error occurs.
f.close()
99.内置exception:
Exception Description
BaseException The root of all exceptions.
GeneratorExit Raised by .close() method on a generator.
KeyboardInterrupt Generated by the interrupt key (usually Ctrl+C).
SystemExit Program exit/termination.
Exception Base class for all non-exiting exceptions.
StopIteration Raised to stop iteration.
StandardError Base for all built-in exceptions (Python 2 only). In Python 3, all exceptions
below are grouped under Exception .
ArithmeticError Base for arithmetic exceptions.
FloatingPointError Failure of a floating-point operation.
ZeroDivisionError Division or modulus operation with 0.
AssertionError Raised by the assert statement.
AttributeError Raised when an attribute name is invalid.
EnvironmentError Errors that occur externally to Python.
IOError I/O or file-related error.
OSError Operating system error.
EOFError Raised when the end of the file is reached.
ImportError Failure of the import statement.
LookupError Indexing and key errors.
IndexError Out-of-range sequence index.
KeyError Nonexistent dictionary key.
MemoryError Out of memory.
NameError Failure to find a local or global name.
UnboundLocalError Unbound local variable.
ReferenceError Weak reference used after referent destroyed.
RuntimeError A generic catchall error.
NotImplementedError Unimplemented feature.
SyntaxError Parsing error.
IndentationError Indentation error.
TabError Inconsistent tab usage (generated with -tt option).
SystemError Nonfatal system error in the interpreter.
TypeError Passing an inappropriate type to an operation.
ValueError Invalid type.
UnicodeError Unicode error.
UnicodeDecodeError Unicode decoding error.
UnicodeEncodeError Unicode encoding error.
UnicodeTranslateError Unicode translation error.
100.自定义exception
class DeviceError(Exception):
def __init__(self, errno, msg):
self.args = (errno, msg) #This attribute is used when printing exception traceback messages. If you leave
#it undefined, users won’t be able to see any useful information about the exception
#when an error occurs.
self.errno = errno
self.errmsg = msg
raise DeviceError(1, 'Not Responding')
101.使用with语句来对系统资源进行自动管理
with open('file.txt') as f:
f.write('log')
# statement
f.write('log2')
import threading
lock = threading.Lock()
with lock
# Critical section
statements
# End critical section
使用with obj语句时,允许obj自动管理该block的进入与离开。当进入该block时,执行obj.__enter__()来通知进入新的block;当离开该block时,执行obj.__exit__(type, value, trackback)来通知离开该block。如果没有exception发生,则这三个参数都设置为None。否则,它们会被设置成exception的type,value,trackback
102.断言assert test [, msg]如果失败,则抛出AssertionError异常。
103.当python运行在优化模式下(-O选项)时,assert不会执行
104.内置只读变量__debug__在优化模式下被设置为False,否则为True。
105.函数的可变参数以*表示
def fprintf(file, fmt, *args):
file.write(fmt, %args)
fprintf(out,"%d %s %f", 42, "hello world", 3.45)
106.如果函数不指定return语句,则默认返回None
107.对于不可变参数,以值传递;对于可变参数,以引用传递
108.以双下划线开头的属性或方法为类的私有方法,如__Foo
109.定义类时,__new__()方法用于创建一个类(类似于构造函数);__init__()方法用于初始化一个类
110.__slot__用于定义类允许的变量,类似于C++/java类的成员变量
class Account(object):
__slots__ = ('name','balance')
111.定义抽象类,使用@abstractmethod修饰符
from abc import ABCMeta, abstractmethod, abstractproperty
class Foo: # In Python 3, you use the syntax
__metaclass__ = ABCMeta # class Foo(metaclass=ABCMeta)
@abstractmethod
def spam(self,a,b):
pass
@abstractproperty
def name(self):
pass
112.可以使用__all__来指定模块允许导出的符号
# module: spam.py
__all__ = [ 'bar', 'Spam' ] # Names I will export with from spam import *
113.sys.path指定python的搜索路径
2.一种更优雅的print方式:
print '%3d %0.2f' %(year, principal) =>
print format(year, '3d'), format(principal, '0.2f')
3.strings也有一个类似的format方法
print '%3d %0.2f' %(year, principal) =>
print '{0:3d}{1:0.2f}'.format(year, principal)
4.pass关键字可以创建一个空语句
if a < b:
pass
else:
print 'Computer says No'
5.使用and/or/not关键字来创建复合表达式
if product == 'game' and type == 'pirate memory' and not (age < 4 or age > 8):
print 'I will take it'
6.python没有case关键字,可以使用elif来实现case的功能
if suffix == ".htm":
content = "text/html"
elif suffix == ".jpg":
content = "image/jpeg"
elif suffix == ".png":
content = "image/png"
else:
raise RuntimeError("Unknown content type")
7.raise产生一个异常,类似于throw
8.使用True和False来表示布尔值
if 'spam' in s:
has_spam = True
else:
has_spam = False
9.in操作符也产生布尔值
has_spam = 'spam' in s;
10.open函数打开一个文件,返回一个文件对象
f = open("foo.txt") # Returns a file object
line = f.readline() # Invokes readline() method on file
while line:
print line, # trailing ',' omits newline character
# print(line,end='') # Use in Python 3
line = f.readline()
f.close()
11.对于集合中元素的遍历,如输入行,数字,字符串集合,python提供for语句来遍历该迭代器,上例可写成:
for line in open('foo.txt')
print line
12.print函数接受一个文件对象参数,来对输出进行重定向
print >> f,"%3d %0.2f" %(year,principal)
python3中格式如下:
print("%3d %0.2f" % (year,principal),file=f)
13.函数对象支持write方法来写入数据,
f.write('%3d %0.2f' %(year, principal))
14.sys模块提供了标准输入/标准输出/标准出错
import sys
sys.stdout.write('Enter your name: ')
sys.stdin.readline()
15.raw_input([prompt])函数也可以实现从标准输入读取数据
name = raw_input('Enter your name: ')
python3中该函数改为input
16.字符串:单引号与双引号作用一样,三引号可以创建跨行字符串。字符串被存储为字符序列,可以通过下标来访问指定位置的字符,下标从0开始
a = 'Hello World'
b = a[4] # b = 'o'
17.字符串分片:s[i:j]
c = a[:5] # c = "Hello"
d = a[6:] # d = "World"
e = a[3:8] # e = "lo Wo"
18.字符串使用+操作符来拼接:
g = a + " This is a test"
19.字符串的+操作符只用于字符串拼接,如果要实现类似整数的+,要先将字符串转化为整数:
x = "37"
y = "42"
z = x + y # z = "3742" (String Concatenation)
z = int(x) + int(y) # z = 79 (Integer +)
20.将其他值转换为字符串的方式:str, repr, format
s = 'The values of x is ' + str(x) #construct a str object using x
s = 'The values of x is ' + repr(x) #Return the canonical string representation of the object
s = 'The values of x is ' + format(x, '3d') #format
str与repr的区别在于:str返回x的print值,而repr返回x在内存中的精确标示,这对双精度数会有不同:
x = 3.4
str(x) => '3.4'
repr(x) => '3.39999999999999999999999999999999'
21.list为任意对象的一个序列,以方括号包围:
names = [ "Dave", "Mark", "Ann", "Phil" ]
通过下标来访问list元素,从0开始:
a = names[2] # Returns the third item of the list, "Ann"
names[0] = "Jeff" # Changes the first item to "Jeff"
22.list追加使用append方法:
names.append("Paula")
23.list插入使用insert方法:
names.insert(2, "Thomas")
24.list切片,类似于字符串的分片
b = names[0:2] # Returns [ "Jeff", "Mark" ]
c = names[2:] # Returns [ "Thomas", "Ann", "Phil", "Paula" ]
names[1] = 'Jeff' # Replace the 2nd item in names with 'Jeff'
names[0:2] = ['Dave','Mark','Jeff'] # Replace the first two items of
# the list with the list on the right.
25.使用+操作符来拼接list
a = [1,2,3] + [4,5] # Result is [1,2,3,4,5]
26.创建空list
names = [] # An empty list
names = list() # An empty list
27.list可以包含任意元素,也可以嵌套list
a = [1,"Dave",3.14, ["Mark", 7, 9, [100,101]], 10]
28.嵌套list的元素通过多重下标来获取
a[1] # Returns "Dave"
a[3][2] # Returns 9
a[3][3][1] # Returns 101
29.list comprehension:
fvalues = [float(line) for line in open(sys.argv[1])]
30.求最大值与最小值:
min(fvalues)
max(fvalues)
31.tuple元组是一系列数据的集合,以小括号包围:
stock = ('GOOG', 100, 490.10)
address = ('www.python.org', 80)
person = (first_name, last_name, phone)
32.没有小括号时,python也能识别出一个元组:
stock = 'GOOG', 100, 490.10
address = 'www.python.org',80
person = first_name, last_name, phone
33.0个元素与1个元素元组的定义方式:
a = () # 0-tuple (empty tuple)
b = (item,) # 1-tuple (note the trailing comma)
c = item, # 1-tuple (note the trailing comma)
34.可以通过数字下标的方式来获取元组的元素,也可以通过如下方式来分解元组
name, shares, price = stock
host, port = address
first_name, last_name, phone = person
35.元组支持像list的大多数操作,如下标,分片,拼接,但元组的内容一旦创建后就不能在修改,即不能修改元素,删除元素,追加元素。
36.list又是会预分配一部分内存,来优化像添加元素这种操作;而由于元组是不可修改的,因此元组使用更加紧凑的方式来存储,没有额外的内存。
37.string.split()函数用于分割字符串,返回一个list
38.集合set是一系列对象的无序集合,通过set()来创建一个集合
s = set([3,5,9,10]) # Create a set of numbers
t = set("Hello") # Create a set of unique characters
39.与list和tuple不同,set中的元素是无序的,因此不能通过下标来访问。并且,set中的元素是唯一不重复的,类似于C++中的set
40.set支持标准的集合操作,如交,差,并,异差
a = t | s # Union of t and s
b = t & s # Intersection of t and s
c = t – s # Set difference (items in t, but not in s)
d = t ^ s # Symmetric difference (items in t or s, but not both)
41.使用add/update来更新set中的元素,使用remove来删除set中的元素
t.add('x') # Add a single item
s.update([10,37,42]) # Adds multiple items to s
42.字典dictionary类似于关联数组或哈希表,通过键来访问值。字典通过大括号包围
stock = {
"name" : "GOOG",
"shares" : 100,
"price" : 490.10
}
通过键作为下标来访问其对应的值:
name = stock["name"]
value = stock["shares"] * shares["price"]
插入和修改也通过键下标来操作
stock["shares"] = 75
stock["date"] = "June 7, 2007"
43.list和dictionary不能作为dictionary的下标,因为他们的内容会改变,而元组可以
44.创建空字典
prices = {} # An empty dict
prices = dict() # An empty dict
45.使用in操作符来测试一个键是否存在于字典中
if 'scox' in prices:
p = prices['scox']
else:
p = 0
46.字典的get方法可以获取某个键对应的值,并提供一个默认值
p = prices.get('scox', 0)
47.使用字典的键创建一个list
syms = list(prices) # syms = ["AAPL", "MSFT", "IBM", "GOOG"]
48.使用del来删除字典的一个键值对
del prices["MSFT"]
49.range( i , j [, stride ])函数创建一个序列,值从i到j-1,stride为增量。如果开始值i省略,则默认为0.如果stride省略,则默认为1
a = range(5) # a = 0,1,2,3,4
b = range(1,8) # b = 1,2,3,4,5,6,7
c = range(0,14,3) # c = 0,3,6,9,12
d = range(8,1,-1) # d = 8,7,6,5,4,3,2
50.python2中range创建非常大的序列时,很耗内存,此时可以使用xrange来代替。python3中xrange即为range,旧range的这种行为已经消除。
51.for循环可以遍历各种对象的序列,如字符串,list,字典,文件
a = "Hello World"
# Print out the individual characters in a
for c in a:
print c
b = ["Dave","Mark","Ann","Phil"]
# Print out the members of a list
for name in b:
print name
c = { 'GOOG' : 490.10, 'IBM' : 91.50, 'AAPL' : 123.15 }
# Print out all of the members of a dictionary
for key in c:
print key, c[key]
# Print all of the lines in a file
f = open("foo.txt")
for line in f:
print line,
52.使用def来定义函数,return返回函数值
def remainder(a,b):
q = a // b # // is truncating division.
r = a - q*b
return r
53.可以使用元组来返回多个值
def divide(a, b):
q = a //b
r = a - q * b
return (q, r)
然后通过如下方式来分解元组
quotient, remainder = divide(1456,33)
54.函数形参可以有默认值
def connect(hostname, port, timeout = 3000):
# function body
调用时可以忽略默认参数
connect('www.python.org', 80)
55.可以通过关键参数以任意顺序来为函数形参赋值
connect(port=80,hostname="www.python.org")
56.函数内部定义的变量为局部变量,作用域为local。如果在函数内部使用全局变量,使用global关键字
count = 0
...
def foo():
global count
count += 1 # Changes the global variable count
57.使用yield语句来实现一个生成器generator,类似于C/C++的static,如fibonacci数列的实现
def fibonacci():
first = 0
second = 1
yield first
while 1:
yield second
first, second = second, first + second
58.yield可以用于创建协程coroutine。
def print_matches(matchtext):
print 'Looking for ', matchtext
while True:
line = (yield)
if matchtext in line:
print line
>>> matcher = print_matches("python")
>>> matcher.next() # Advance to the first (yield)
Looking for python
>>> matcher.send("Hello World")
>>> matcher.send("python is cool")
python is cool
>>> matcher.send("yow!")
>>> matcher.close() # Done with the matcher function call
>>>
59.dir()函数可以列出对象的所有可执行方法及全局变量
60.对象内的下划线方法定义了给类型的操作符,如__add__()方法实现了+操作符
61.class关键字用于定义一种新的数据类型
class Stack(object):
def __init__(self):
self.stack = [] # Initialize the stack
def push(self, object):
self.stack.append(object)
def pop(self):
return self.stack.pop()
def length(self):
return len(self.stack)
62.class定义类型中,小括号表示继承,即Stack继承object。object是所有python对象的根对象。所有函数的第一个成员都表示该对象自身,即C++中的this。默认情况下使用self。
63.@staticmethod修饰符可以指示创建静态方法
class EventHandler(handler):
@staticmethod
def dispatcherThread():
# wait for request
EventHandler.dispatcherThread() # call method like a function
64.使用try/except来捕获异常
try:
f = open('file.txt', 'r')
except IOError as e:
print e
65.使用raise来抛出一个异常
raise RuntimeError('Computer says no')
66.使用with语句来管理系统资源,如锁,文件,网络连接等
import threading
message_lock = threading.lock
......
with message_lock:
message.add(newmessage)
当进入with语句块时,锁会自动获取;当离开语句块时,锁会自动释放。
67.使用import...as...对倒入的模块重命名
import div as foo
a, b = foo.divide(2305, 29)
68.加载模块的内容到当前的命名空间,使用from ... import ...
from div import divide
a, b = divide(2305, 29)
加载模块的所有内容,使用
from div import *
69.使用help()来查看某一个模块的帮助
70.使用pydoc命令来查看摸个模块的doc文档
71.块缩进的数量没有限制,但同一块代码的缩进必须相同
72.尽量不要用tab来做缩进
73.以-t选项运行python时,对于tab与空格混用的情况,python会产生一个warning;以-tt选项允许python时,python会产生TabError
74.同一行的多个语句,需要以分号分割
75.标识符职能包括字符,数字,下划线,且只能以字符或下划线开头
76.标识符大小写敏感
77.python保留字:
and del from nonlocal try
as elif global not while
assert else if or with
break except import pass yield
class exec in print
continue finally is raise
def for lambda return
78.以单下划线开头的标识符如_foo,在使用from ... import *时,不会被导入;前后双下划线标识符如__init__保留用作特殊方法;双下划线开头的标识符如__bar用于标识类的私有方法
79.四种内置整数类型
Boolean:True False
Integer
Floating-point number
Comples number
80.二进制整数以0b开头;八进制整数以0开头;十六进制整数以0x开头
81.模块,类,方法定义时的第一句话如果是一条字符串,该字符串就是该对象的doc
def fact(n):
''' This function computes a factorial '''
if n <= 1:
return 1
else:
return n * fact(n - 1)
82.修饰符可以用于修饰函数,方法,或类定义
83.在文档的第一或第二行使用编码注释来制定文档的编码方式
#!/usr/bin/python
# -*- coding: UTF-8 -*-
s = "Jalape?o" # String in quotes is directly encoded in UTF-8.
84.对象的标识可以看成对象在内存中的位置指针
85.内置函数id()返回对象的identity整数值;该整数值通常对应于该对象在内存中的位置;
86.is 操作符用于比较两个变量是否指向同一个对象
87.内置函数type()返回对象的类型
# Compare two objects
def compare(a,b):
if a is b:
# a and b are the same object
statements
if a == b:
# a and b have the same value
statements
if type(a) is type(b):
# a and b have the same type
statements
88.内置函数isinstance(object, type)判断对象是否是某一个类型
if isinstance(s, list):
s.append(item)
if isinstance(d, dict):
d.update(t)
89.python中所有对象采用引用计数;sys.getrefcount(object)函数可以查看对象的引用计数。当计数值为0时,该对象可以被gc回收
90.对于不可变对象如数字,字符串,元组,赋值操作创建对象的一份拷贝;对于可变对象如list,字典,仅仅是创建一个指向对象的引用
>>> a = [1,2,3,4]
>>> b = a # b is a reference to a
>>> b is a
True
>>> b[2] = -100 # Change an element in b
>>> a # Notice how a also changed
[1, 2, -100, 4]
>>>
91.容器对象的浅拷贝与深拷贝:浅拷贝只创建一个对象,对象内部的元素是指向原对象内部元素的引用
>>> a = [ 1, 2, [3,4] ]
>>> b = list(a) # Create a shallow copy of a.
>>> b is a
False
>>> b.append(100) # Append element to b.
>>> b
[1, 2, [3, 4], 100]
>>> a # Notice that a is unchanged
[1, 2, [3, 4]]
>>> b[2][0] = -100 # Modify an element inside b
>>> b
[1, 2, [-100, 4], 100]
>>> a # Notice the change inside a
[1, 2, [-100, 4]]
>>>
深拷贝创建一个对象,并递归式拷贝其内部的所有对象
>>> import copy
>>> a = [1, 2, [3, 4]]
>>> b = copy.deepcopy(a)
>>> b[2][0] = -100
>>> b
[1, 2, [-100, 4]]
>>> a # Notice that a is unchanged
[1, 2, [3, 4]]
>>>
92.通过copy模块的deepcopy方法来实现深拷贝
93.python内置类型
Type Category Type Name Description
None type(None) The null object None
Numbers int Integer
long Arbitrary-precision integer (Python 2 only)
float Floating point
complex Complex number
bool Boolean ( True or False )
Sequences str Character string
unicode Unicode character string (Python 2 only)
list List
tuple Tuple
xrange A range of integers created by xrange() (In Python 3, it is called range. )
Mapping dict Dictionary
Sets set Mutable set
frozenset Immutable set
94.序列类型的通用操作
Item Description
s [ i ] Returns element i of a sequence
s [ i : j ] Returns a slice
s [ i : j:stride ] Returns an extended slice
len( s ) Number of elements in s
min( s ) Minimum value in s
max( s ) Maximum value in s
sum( s [, initial ]) Sum of items in s
all(s) Checks whether all items in s are True .
any(s) Checks whether any item in s is True
s [ i ] = v Item assignment
s [ i : j ] = t Slice assignment
s [ i : j:stride ] = t Extended slice assignment
del s [ i ] Item deletion
del s [ i : j ] Slice deletion
del s [ i : j:stride ] Extended slice deletion
95.list操作
Method Description
list( s ) Converts s to a list.
s .append( x ) Appends a new element, x , to the end of s .
s .extend( t ) Appends a new list, t , to the end of s .
s .count( x ) Counts occurrences of x in s
s .index( x [, start [, stop ]]) Returns the smallest i where s [ i ]== x . start and stop optionally specify the starting
and ending index for the search. a ValueError exception is raised if not found
s .insert( i,x ) Inserts x at index i .
s .pop([ i ]) Returns the element i and removes it from the list. If i is omitted, the last element is
returned. Raises IndexError if list is empty or index is out of range.
s .remove( x ) Searches for x and removes it from s . a ValueError exception is raised if not found
s .reverse() Reverses items of s in place. return none
s .sort([ key [, reverse ]]) Sorts items of s in place. key is a key function. reverse is a flag that sorts the list in
reverse order. key and reverse should always be specified as keyword arguments. return none
96.函数
abs( x ) Absolute value
divmod( x , y ) Returns (x // y, x % y )
pow( x , y [, modulo ]) Returns ( x ** y ) % modulo
round( x ,[ n ]) Rounds to the nearest multiple of 10 -n (floating-point numbers only)
97.enumerate(sequence)函数用于产生序列的元组,如(0, s [0]) ,(1, s [1]) , (2, s [2])等等
98.try/except/else/finally
try:
f = open('file.txt')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else: #This code is executed if the code in the try block doesn’t raise an exception.
data = f.read()
finally: #This code is executed regardless of whether an error occurs.
f.close()
99.内置exception:
Exception Description
BaseException The root of all exceptions.
GeneratorExit Raised by .close() method on a generator.
KeyboardInterrupt Generated by the interrupt key (usually Ctrl+C).
SystemExit Program exit/termination.
Exception Base class for all non-exiting exceptions.
StopIteration Raised to stop iteration.
StandardError Base for all built-in exceptions (Python 2 only). In Python 3, all exceptions
below are grouped under Exception .
ArithmeticError Base for arithmetic exceptions.
FloatingPointError Failure of a floating-point operation.
ZeroDivisionError Division or modulus operation with 0.
AssertionError Raised by the assert statement.
AttributeError Raised when an attribute name is invalid.
EnvironmentError Errors that occur externally to Python.
IOError I/O or file-related error.
OSError Operating system error.
EOFError Raised when the end of the file is reached.
ImportError Failure of the import statement.
LookupError Indexing and key errors.
IndexError Out-of-range sequence index.
KeyError Nonexistent dictionary key.
MemoryError Out of memory.
NameError Failure to find a local or global name.
UnboundLocalError Unbound local variable.
ReferenceError Weak reference used after referent destroyed.
RuntimeError A generic catchall error.
NotImplementedError Unimplemented feature.
SyntaxError Parsing error.
IndentationError Indentation error.
TabError Inconsistent tab usage (generated with -tt option).
SystemError Nonfatal system error in the interpreter.
TypeError Passing an inappropriate type to an operation.
ValueError Invalid type.
UnicodeError Unicode error.
UnicodeDecodeError Unicode decoding error.
UnicodeEncodeError Unicode encoding error.
UnicodeTranslateError Unicode translation error.
100.自定义exception
class DeviceError(Exception):
def __init__(self, errno, msg):
self.args = (errno, msg) #This attribute is used when printing exception traceback messages. If you leave
#it undefined, users won’t be able to see any useful information about the exception
#when an error occurs.
self.errno = errno
self.errmsg = msg
raise DeviceError(1, 'Not Responding')
101.使用with语句来对系统资源进行自动管理
with open('file.txt') as f:
f.write('log')
# statement
f.write('log2')
import threading
lock = threading.Lock()
with lock
# Critical section
statements
# End critical section
使用with obj语句时,允许obj自动管理该block的进入与离开。当进入该block时,执行obj.__enter__()来通知进入新的block;当离开该block时,执行obj.__exit__(type, value, trackback)来通知离开该block。如果没有exception发生,则这三个参数都设置为None。否则,它们会被设置成exception的type,value,trackback
102.断言assert test [, msg]如果失败,则抛出AssertionError异常。
103.当python运行在优化模式下(-O选项)时,assert不会执行
104.内置只读变量__debug__在优化模式下被设置为False,否则为True。
105.函数的可变参数以*表示
def fprintf(file, fmt, *args):
file.write(fmt, %args)
fprintf(out,"%d %s %f", 42, "hello world", 3.45)
106.如果函数不指定return语句,则默认返回None
107.对于不可变参数,以值传递;对于可变参数,以引用传递
108.以双下划线开头的属性或方法为类的私有方法,如__Foo
109.定义类时,__new__()方法用于创建一个类(类似于构造函数);__init__()方法用于初始化一个类
110.__slot__用于定义类允许的变量,类似于C++/java类的成员变量
class Account(object):
__slots__ = ('name','balance')
111.定义抽象类,使用@abstractmethod修饰符
from abc import ABCMeta, abstractmethod, abstractproperty
class Foo: # In Python 3, you use the syntax
__metaclass__ = ABCMeta # class Foo(metaclass=ABCMeta)
@abstractmethod
def spam(self,a,b):
pass
@abstractproperty
def name(self):
pass
112.可以使用__all__来指定模块允许导出的符号
# module: spam.py
__all__ = [ 'bar', 'Spam' ] # Names I will export with from spam import *
113.sys.path指定python的搜索路径