1. 数字:
decimal.Decimal('1.1')
是1.1,不会是1.10000000001
2. Print:
print 等于 print '\n'
>>> print “good!” if 8 == number else “bad!”
字典可以用变量名直接格式化输出
table = {‘Jack’: 4098,}
print ‘Jack: %(Jack)d’ % table
3. 在循环中修改列表的内容,用副本修改
>>> a = [“cat”, “dog”]
>>> for x in a[:]:
… if len(x) < 6:
… a.insert(0,x)
4. 对于List:
extend(L) 追加列表
count(x) x出现次数
[::-1] 倒序
5. 创建字典:
tel.fromkeys([1, 2], 0) => {1: 0, 2: 0}
6. 函数参数
func(*para, **paras) 元组, 字典
eg: test(“yes”, 1, 2, me = “xxx”, where = “China”)
7. eval() 对字符串参数运算求值
exec() 将字符串参数作脚本执行,execfile()
8. 装饰器:
@A def B: pass == def B: pass B = A(B)
eg: 测试运行时间
from time import time
def cost_time(func):
def result(*args, **dic):
begin = time()
func(*args, **dic)
print “cost time: “, time() – begin
return result
@cost_time
def show(n):
for x in range(n):
print x
9. 生成器表达式
eg:
unique_words = set(word for line in file for word in line.split())
10. Filter:
filter(func, seq) 返回seq中使func返回True的值
eg:
a = [1, 2, 3, 4]
filter(lambda x : x % 2, a) => [1, 3]
11. Map:
eg:
map(lambda x, y, z: x + y + x, range(1, 3), range(3, 5), range(5, 7)) => [9, 12]
12. Reduce:
eg:
reduce(lambda x, y: x + y, range(3), 99) == sum(range(3), 99)
过程:99 + 0 = 99 -> 99 + 1 = 100 -> 100 + 2 = 102
13. 多个seq的循环:
questions = [“name”, “quest”]
answers = [“rae”, “ok”]
for q, a in zip(questions, answers):
print “what is your %s? It is %s” % (q, a)
14. 列表循环输出索引位置和对应的值:
for i, v in enumerate([‘a’, ‘b’, ‘c’]):
print i, v
16. 包:
生成包,目录下有__init__.py, 该文件中有__all__ = [“file1”, “file2”, ]
17. 编码:
# -*- coding: utf-8 -*-
网络编程可用gbk
18. bisect 二分查找实现
bisect.insort(list, element) 快速插入有序序列
参照
python基础学习:
http://wiki.woodpecker.org.cn/moin/PyAbsolutelyZipManual
《Python核心编程(第二版)》
C程序员转Python程序员需要注意:
1. python不支持++和--操作
2. 有bool型,C++也有