Python 入门
数据类型
- 不可变对象:自身的内容不可变
- 可变对象:自身的内容可变
-
检查对象的类型type()
- Numeric Types:int,float,complex
- Sequence Types:list,tuple,range
数字类型 不可变对象
- 整型 int
- 浮点型 float 1.23, -9.01 1.23e9 12.3e8 1.2e-5 浮点型还包括: Infinity/inf nan(not a number),case(大小写) is not significant float(‘-Infinity’) -inf
- 复数 a+bj a(real属性)实部 b(imag属性)虚部 十六进制0x 八进制0o 二进制0b 转换:int(x) float(x) complex(re,im) 数学运算:
+ - * / //(整除,向下取整)
%(取余) **(幂) abs(x)(绝对值,复数的模)
- +
divmod(x,y)=(x//y,x%y) pow(x,y)
定义:pow(0,0)=1,0**0=1,as is common for programming languages. 数学函数
max(iterable)
max(arg1,arg2,*args)
min()
round()
sum()
from math import *
floor()
ceil()
字符串类型 str 不可变对象
转义符:
表示:’ab’ “abc”
索引起始:0
正向索引:0~L-1
反向索引:-L~-1
ord(chr)获取字符对应的整数(ASCII字符返回ASCII码值)
chr(num)获取整数对应的字符
运算:
+(concatenate) *(dup) len(str)
转换:str(obj)
方法:
upper()
lower()
strip() #(去两边空格,去头尾指定字符)
split() #(指定字符将字符串分为列表)
join() #(用该字符将列表联合)
find(sub[,start,end])#(搜索指定子串,返回第一次出现的位置,若无,返回-1)
replace(old,new[,count])#(将所有旧项用新项替换)
for var in string #迭代格式
列表 list 可变对象
列表是有序的元素的集合,元素类型可以不同
a=[0,1,2,3]
a=[] #空
运算:
+ * 切片 len()
for <var> in <list> #迭代
<expr> in <list> #成员列举
转换:list() 方法
append(x) #将元素x增加到列表的最后
sort(key=None,reverse=False)
#排序key:排序关键字,函数指针,reverse:是否颠倒
reverse()
index(x) #放回第一次出现元素x的索引值
insert(i,x) #在位置i插入元素x i可取0到无穷,大于等于数组长度插在最后
count(x) #返回x出现的次数
remove(x) #删除列表中第一次出现的元素x
pop([i]) #取出位置为i的元素,并删除,默认最后一个
copy() #返回list的shallow copy.Equivalent to a[:].
元组 tuple 不可变对象
元组可以包含多种元素类型,元组外侧可以使用括号,也可以不使用, 但元组作其他元组元素的时候要加括号 转换:tuple()
#表示
t1=123,456,"hello"
t2=() #空
t3=(123,) #单元素
t4=123,456,('hello','world')
字典 dict 可变对象
使用键-值(key-value)存储,有极快的查找速度,无序 key必须为不可变对象,如整数,字符串 表示:d={‘Michael’:95,’Bob’:75,’Tracy’:85} 转换:dict()
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
#When the keys are simple strings,
#it is sometimes easier to specify pairs using keyword arguments
dict(sape=4139, guido=4127, jack=4098)
d={'Michael':95,'Bob':75,'Tracy':85}
d['Michael'] #95
#方法
d['yu']=100 #增加记录
del d['yu'] #删除记录
d.get('Tomas') #不存在返回None,安全,避免key不存在
d.pop('Bob') #获得值并删除记录
d.keys() #返回dict_keys对象
d.values() #返回dict_values对象
d.items() #返回dict_items对象
for k, v in d.items():
print(k, v)
'yu' in d #存在性判断
'Bob' not in d #不存在性判断
#enumerate函数将list变为索引,元素对
for i,value in enumerate(['a','b','c']):
print(i,value)
集合 set
与数学中定义的集合相同,无重复,集合中的每个字都称为key 表示:s={a,b,c} 转换:set()
s=set([1,2,3])
#运算
& | - ^ #交 并 差 对称差
a = {x for x in 'abracadabra' if x not in 'abc'}
#{'r', 'd'}
程序元素
- 注释 单行以#开头,多行以’'’开头和结尾,文档注释一般以”"”开头和结尾 函数的注释存储在函数的__doc__变量中
- 缩进 1缩进=4空格
- 表达式 变量无须定义,但在使用前需要先赋值
- 逻辑运算 and or not 执行短路运算
- 关系运算
< <= > >= == != is is not
#大小由下列函数定义
__lt__ __le__ __gt__ __ge__
__eq__ ...
- 位运算 A left shift by n bits is equivalent to multiplication by pow(2, n) without overflow check. A right shift by n bits is equivalent to division by pow(2, n) without overflow check.
| ^ & << >> ~
#位或 位异或 位交 左移 右移 位反
- 输入input var=input([prompt])
- 输出print
print('The average number is %f'%avg_num)
- 赋值语句 var=expr 同步赋值语句(将右侧的n个表达式打包成tuple,再赋给左边 var1,var2,…,varn=expr1,expr2,…,exprn
- 分支语句
if test1:
expr1
elif test2:
expr2
...
else:
exprn
- 循环语句
for i in range(<count>):
<expr>
for x in <list>:
<expr>
while <testexpr>:
<expr>
break,continue,else 也可以有
#else子句在for语句正常退出(非break)时执行
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
-
作用域
- 函数库(包)
自带的:math,random,turtle等
其他的:自行安装
import package
from package import name/* (所有函数)
第二种方式不需要使用库名
if __name__=='__main__': test() #自己运行该程序是运行test(),被导入模块时不执行
- del This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list.
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0] #[1, 66.25, 333, 333, 1234.5]
del a[2:4] #[1, 66.25, 1234.5]
del a[:] #[]a为空list
del a #a不存在了
函数
函数名:即函数指针 返回值:无返回值即返回None,空return也是返回None,可以返回多值,自动打包成一个tuple
def name(<param>):
expr
return #等价于return None 等价于无return
- 空语句 pass
- 函数参数
- 位置参数:即按位置依次传入的参数power(x,y)
-
默认参数: 必选参数在前,默认参数在后power(x,y=2) 天坑:默认参数必须指向不可变对象 Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
def f(a, L=[]): L.append(a) return L print(f(1)) #[1] print(f(2)) #[1,2] print(f(3)) #[1,2,3] #解决方法 def f(a, L=None): if L is None: L = [] L.append(a) return L
- 可变参数:*args arg(arguments)是可变参数,接受任意多个参数,组成一个tuple * 为解包运算,将一个sequence解包成一个个的元素
- 关键字参数 **kw 关键字参数会组装成一个dict
- 函数的docstring和annotation
def my_function():
"""Do nothing, but document it.
No, really, it doesn't do anything. """
pass
my_function.__doc__
#"Do nothing, but document it.\n\n No, really, it doesn't do anything. "
def f(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:", f.__annotations__)
print("Arguments:", ham, eggs)
return ham + ' and ' + eggs
f.__annotations__
#{'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
文件读写
f=open(filename,mode)#f是一个文件指针 mode:r,w,r+,
f.read(<size>)#size为空则读取全部文件,size的单位Byte
f.readline() #读取一行
#if f.readline() returns an empty string,
#the end of the file has been reached
f.readlines() #读取所有行,返回一数组
f.write('This is a test\n') #写
#好的写法:
for line in f:
print(line, end='')
#读完后自己关闭
with open('workfile') as f:
read_data = f.read()
无拷贝,浅拷贝和深拷贝
no copy,shallow copy 与deep copy
浅拷贝—— 在拷贝出的新的对象上插入(引用)源list对象的一切; 深拷贝—— 递归地拷贝源list对象中的一切。(彻头彻尾的另立门户)。
import copy
will = ["Will", 28, ["Python", "C#", "JavaScript"]]
w=will #w是无拷贝
wilber=will.copy() #willer是浅拷贝
willhard=copy.deepcopy(will) #wiihard是神拷贝
will[2][0]="OK"
will
# ['Will', 28, ['OK', 'C#', 'JavaScript']]
wilber
# ['Will', 28, ['OK', 'C#', 'JavaScript']]
w[0]='No'
w
#['No', 28, ['OK', 'C#', 'JavaScript']]
will
#['No', 28, ['OK', 'C#', 'JavaScript']]
wilber
#['Will', 28, ['OK', 'C#', 'JavaScript']]
数据结构的实现
- stack
stack = [3, 4, 5]
stack.append(6) #[3,4,5,6]
stack.append(7) #[3, 4, 5, 6, 7]
stack.pop() #[3,4,5,6]
stack.pop() #[3,4,5]
- queue
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queue.popleft() #return: 'Eric' queue:['John','Michael','Terry']
错误处理
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError: #(RuntimeError, TypeError, NameError)
print("Oops! That was no valid number. Try again...")
高级特性
匿名函数 lambda表达式
retval=lambda arg1,arg2,...,argn:retval
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
# [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
高级函数
- sorted() 排序
sorted([-1,1,0])
#[-1,0,1] 升序 ascending order
sorted(L,key=func) #按函数值大小排序
- map(func,*iterables) 映射
t=(map(lambda x: x**2, range(10)) #map object,属于iterator
squares=list(t)
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- reduce(f,L) 迭代
from functools import reduce
#reduce(f,[x1,x2,x3,x4])=f(f(f(x1,x2),x3),x4)
def fn(x,y):
return x*10+y
reduce(fn,[1,3,5,7,9]) #返回一个值
- filter(f,L) 过滤器 其中f的返回值是bool类型值,将真留下,将假舍去 返回filter object,是iterator
列表生成式
(类似数学中的函数)List Comprehensions 类似 y=x x in range()
[x*x for x in range(1,11)]
[x*x for x in range(1,11) if x%2==0]
[m+n for m in 'abc' for n in 'xyz']
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
#equivalent to
combs = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
- 嵌套的列表生成式 Nested List Comprehensions
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
#转置:
[[row[i] for row in matrix] for i in range(4)]
#equivalent to
transposed = []
for i in range(4):
transposed.append([row[i] for row in matrix])
#equivalent to
transposed = []
for i in range(4):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
#equivalent to
list(zip(*matrix))
#[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
迭代器与生成器 iterator and generator
面向对象
动态语言的特性:属性可以动态绑定 变量的作用域 __xxx 是private变量
- 对象数据类型的判断isinstance,type isinstance: 子类的数据类型可以被看做父类的数据类型,反之不成立 type:严格的类型相同
# Dog是Animal的子类
isinstance(b,Dog) #True
isinstance(b,Animal) #True
type(123)==int #True
type('abc')==str #True
type([1,2,3],(list,tuple)) #true
杂项
- sep=separetor
- 帮助 help([object]) Invoke the built-in help system. help(str)
- pip 目录:C:\Program Files\Python36\Scripts。基本用法:
- pip install package
- pip list
- pip uninstall package
- The folloing values are considered false:
- None
- False
- zero of any numeric type, for example, 0, 0.0, 0j.
- any empty sequence, for example, ‘’, (), [].
- any empty mapping, for example, {}.
- instances of user-defined classes, if the class defines a bool() or len() method, when that method returns the integer zero or bool value False.