一些个人容易理解,与java没有太大区别的内容,我就不一一仔细去看了,最主要的还是去比较与之前学过java的不同。
切片
想从一个list或者tuple中取想要的元素怎么办,那当然毫无疑问的list[0],通过索引取我们想要的元素,但是如果我们是想取某个索引范围内的元素,那怎么办。这个时候就引入了切片,可以看到下面一些基本操作,可以说是非常方便。
>>> names=["Jack","Michal","Tom","Henry","Marry"]
>>> names[1:3]
['Michal', 'Tom']
>>> names[1:]
['Michal', 'Tom', 'Henry', 'Marry']
>>> names[:4]
['Jack', 'Michal', 'Tom', 'Henry']
>>>
迭代
判断可迭代对象
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
Python内置的enumerate
函数可以把一个list变成索引-元素对,这样就可以在for
循环中同时迭代索引和元素本身:>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
列表生成式
如果是想生成[1*1,2*2,3*3...9*9]这样的
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [m+n for m in "abc" for n in "ABC"] #两层列表
['aA', 'aB', 'aC', 'bA', 'bB', 'bC', 'cA', 'cB', 'cC']
当然可以加上if条件进行过滤啦>>> [x for x in range(1,101) if x%2==0]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
生成器 generator
generator和函数的执行流程不一样。函数是顺序执行,遇到return
语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()
的时候执行,遇到yield
语句返回,再次执行时从上次返回的yield
语句处继续执行。
def triangles():
L=[1]
i=0;
while i<10:
yield L
L=[1]+[L[i]+L[i+1] for i in range(i)]+[1]
i=i+1
for n in triangles():
print(n)
输出结果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
迭代器 Iterator
list,set,dict是iterable但不是Iterator,把list
、dict
、str
等Iterable
变成Iterator
可以使用iter()
函数:
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
except StopIteration:
# 遇到StopIteration就退出循环
break
高阶函数
map/reduce
先看map,map接受两个参数,一个是Iterable,一个是函数,将函数作用在Iterable中的每一个元素上,并以iterable返回
>>>def fun(x):
return x*x
>>>r=map(fun,[1,2,3,4,5])
>>>list(r)
[1,4,9,16,25]
再来看reduce,reduce也是接受两个参数,把结果继续和序列的下一个元素做累积计算,其效果就是:reduce(f,[x1,x2,x3,x4,x5])=f(f(f(f(x1+x2)+x3)+x4)+x5)
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])#((((1+3)+5)+7)+9)
25