Python学习手册

2013-10-11 15:13  2847人阅读  评论 (0)
Tags: python

Python学习手册

运行python

交互模式

$ python
>>> s = '123456'
>>> s
123456

系统命令执行

python hello.py

可执行脚本

#!/usr/bin/python
#!/usr/bin/env python
print('Hello World!')

$ chmod +x hello.py
$ ./hello.py

双击运行

windows

模块导入

$ python
>>> import hello
Hello World!

exec运行文件

$ python
>>> execfile('hello.py') # 2.7
Hello World!
>>> exec file('hello.py') # 2.7
Hello World!
>>> exec(open('hello.py').read()) # 2.7, 3.0

编辑器EDLE

Alt+P Alt+N

导入模块

import sys
sys.getcwd()

dir函数

打印对象的所有方法

help函数

打印函数或对象的帮助信息

Python内置类型

数字
字符串             'span', "guido's", b'a\xolc'
列表              [1, [2, 'three'], 4]
字典              {'food':'spam', 'taste':'yum'}
元组              (1, 'span', 4, 'U')
文件              myfile = open('log.txt', 'w')
集合              set('abc'), {'a', 'b', 'c'}
其他类型            类型,None,布尔型
编程单元类型      函数,模块,类
与实现相关的类型    编译的代码堆栈跟踪

数字 number

len(str(2 ** 100))          # 长度
import math
math.pi
math.sqrt(4)
import random
random.random()             # 随机数 0-1的float
random.choice([1,2,3,4,5])  # 随机一个元素

字符串 string

S = 'Spam'
len(S)
S[0]
S[-1]
S[1:3]      # 切片 slice
S+'xyz'     # 连接
S*8         # 重复
S[0] = '1'  # ERROR

S.find('pa')
S.replace('pa', 'XYZ')
S.split('a')
S.upper()
S.lower()
S.isalpha()
S.strip() // trim函数 lstrip() lstrip()

msg = """<dir>
hello world!
</div>"""   # 文本块

正则表达式 RegExp

import re
m = re.match('Hello (.*) world', 'Hello Python world')
m.group(1)

列表 list

L = [123, 'spam', 1.23]
len(L)
L[0]
L[:-1]
L + [4, 5, 6]
L2 = L * 10

L.append('ni')
L.pop(3)
L.sort()
L.reverse()

# 遍历数组
L = [[1,2,3],[4,5,6],[7,8,9]]
[row[0] for row in L]
[row[1] for row in L if row[1] % 2 == 0]

# 迭代器
I = (sum(row) for row in L)
next(I)

# 遍历
map(sum, L)

# 列表 to 集合
{sum(row) for row in L}

# 列表 to 字典
{i : sum(L[i]) for i in range(3)}

字典 dict

M = {'b':2, 'c':3, 'a':1}
M.items()
M.iteritems()
M.keys()
M.iterkeys()
M.values()
M.itervalues()
[k for k in M]
[k*v for k,v in M.items()]

迭代器和优化 iterator

squares = [x ** 2 for x in [1,2,3,4,5,6]]

if else elif

'b' in M
if not 'b' in M:
    print('missing')
v = M.get('d', 4)
v = M['d'] if 'd' in M else 4

元组 tuple

元组不可变

T = (1, 2, 3, 4)
len(T)
T + (5, 6)
T[0]

文件 file

f = open('data.txt', 'w')
f.write('hello world!\n');
f.close()

f = open('data.txt', 'r')
print(f.read());
f.close()

集合 set

X = set('spam')
Y = {'h', 'a', 'm'}

X & Y
X | Y
X - Y

浮点数 float

1.0 / 3     # 0.3333333333333333

# 十进制
import decimal
decimal.Decimal('1') / decimal.Decimal('3')
# output: Decimal('0.3333333333333333333333333333')
decimal.getcontent().prec = 2
decimal.Decimal('1') / decimal.Decimal('3')
# output: Decimal('0.33')

# 分数
from fractions import Fraction
f = Fraction(2, 3)  # 2/3
f + 1               # Fraction(5, 3)
f + Fraction(1, 2)  # Fraction(7, 6)

布尔值 bool

Ture, False

没有 None

X = None

如何破坏代码的灵活性

type(L)         # 2.6 output: <type 'list'>
type(type(L))   # 2.6 output: <type 'type'>

type(L)         # 3.0 output: <class 'list'>
type(type(L))   # 3.0 output: <class 'type'>

if type(L) == type([]) :    # Type testing, if you must ...
    print('yes')
if type(L) == list :        # Using the type name
    print('yes')
if isinstance(L, list) :    # Object-oriented tests
    print('yes')
豫ICP备09035262号-1