Python 入门

数据类型

数字类型 不可变对象

+ - * / //(整除,向下取整)
 %(取余) **() 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'}

程序元素

< <= > >= == != is is not

#大小由下列函数定义
__lt__ __le__ __gt__ __ge__
__eq__ ...
| ^ & << >> ~
#位或 位异或 位交 左移 右移 位反
print('The average number is %f'%avg_num)
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')

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
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 = [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]
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([-1,1,0])
#[-1,0,1] 升序 ascending order
sorted(L,key=func) #按函数值大小排序
t=(map(lambda x: x**2, range(10)) #map object,属于iterator
squares=list(t)
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
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]) #返回一个值

列表生成式

(类似数学中的函数)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)]
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变量

# 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

杂项