(一)基本数据类型
-
list
1.1 list是一种有序的集合,可以随时添加和删除其中的元素
1.2>>> classmates = ['Michael', 'Bob', 'Tracy'] >>> classmates ['Michael', 'Bob', 'Tracy']
len()
函数可以获取list元素的个数
1.3 用>>> len(classmates) 3
索引
来访问list中每个位置的元素
1.4 用-1作索引,直接访问最后一个元素>>> classmates[0] 'Michael'
1.5 追加元素>>> classmates[-2] 'Bob' >>> classmates[-3] 'Michael'
1.6 插入元素>>> classmates.append('Adam')
1.7 删除末尾>>> classmates.insert(1, 'Jack')
1.8 删除指定位置元素>>> classmates.pop()
>>> classmates.pop(1)
-
tuple
2.1 tuple一旦初始化就不能修改,没有append(),insert()这样的方法
2.2 因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。
2.3 定义
2.4 空的tuple>>> t = (1, 2) >>> t (1, 2)
2.5 一个元素的tuple>>> t = () >>> t ()
2.6 ‘可变的’tuple(通过list)>>> t = (1, ) >>> t (1, )
>>> t = ('a', 'b', ['A', 'B']) >>> t[2][0] = 'X' >>> t[2][1] = 'Y' >>> t ('a', 'b', ['X', 'Y'])
-
dict
3.1 使用键-值(key-value)存储,具有极快的查找速度。需要占用大量的内存,内存浪费多。
3.2 避免key不存在报错>>> d = {'Michael' : 95, 'Bob' : 75, 'Tracy' : 85} >>> d['Michael'] 95
- 通过
in
判断
3.3 通过>>> 'Thomas' in d False
get()
判断
3.4 删除>>> d.get('Thomas') >>> d.get('Thomas', -1) -1
>>> d.pop('Bob') 75
- 通过
-
set
4.1 set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
4.2 创建
4.3 自动过滤>>> s = set([1, 2, 3]) >>> s {1, 2, 3}
4.4 添加>>> s = set([1, 1, 2, 2, 3, 3]) >>> s {1, 2, 3}
add
4.5 删除>>> s.add(4) >>> s {1, 2, 3, 4} >>> s.add(4) >>> s {1, 2, 3, 4}
remove
4.6 交集、并集>>> s.remove(4) >>> s {1, 2, 3}
>>> s1 = set([1, 2, 3]) >>> s2 = set([2, 3, 4]) >>> s1 & s2 {2, 3} >>> s1 | s2 {1, 2, 3, 4}
(二) 常用函数
对于不可变对象,调用对象自身的任意方法,也不会改变对象自身的内容。相反,这些方法会创建新的对象并返回,这样,就保证了不可改变对象本身永远不可变的。
>>> a = 'abc'
>>> b = a.replace('a', 'A')
>>> b
'Abc'
>>> a
'abc'
>>> abs(100)
100
>>> abs(-20)
20
>>> abs(12.34)
12.34
>>> max(1, 2)
2
>>> max(2, 3, 1, -5)
3
>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False
>>> a = abs
>>> a(-1)
1
>>> n = 255
>>> hex(n)
0xff
def my_abs(x):
if x >= 0:
return x
else:
return -x
>>> print(my_abs(-99))
99
>>> from abstest import my_abs
>>> my_abs(-99)
>99
还没想好代码怎么写时,可以先放一个pass
,让代码先能够运行起来
def nop():
pass
实质是返回一个tuple
import math
def move(x, y, step, angle=0)
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0
默认参数必须指向不可变对象
def power(x, n=2)
s = 1
while n > 0:
n = n - 1
s = s * x
return s
>>> power(5)
25
>>> power(5, 2)
25
默认
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
>>> calc([1, 2, 3])
14
>>> calc((1, 3, 5, 7))
84
可变
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
>>> calc(1, 2, 3)
14
>>> calc(1, 3, 5, 7)
84
# 如果要传一个list或者tuple
>>> nums = [1, 2, 3]
>>> calc(nums[0], nums[1], nums[2])
14
>>> nums = [1, 2, 3]
>>> calc(*nums)
14
允许传入0个或任意个含参数名的参数,在函数内部会自动组组装为dict
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
>>> person('Michael', 30)
name:Micael age:30 other:{}
>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, city=extra['city'], job=extra['job'])
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
#**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra。
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
命名关键字参数必须传入参数名
命名关键字参数需要一个特殊分隔符*
,*
后面的参数被视为命名关键字参数。
def person(name, age, *, city, job):
print(name, age, city, job)
>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer
如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*
了
def person(name, age, *args, city, job):
print(name, age, args, city, job)
参数组合
参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
>>> fact(1)
1
>>> fact(5)
120
防止栈溢出,尾递归优化
在函数返回的时候,调用自身本身,并且,return语句不能包含表达式
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)