1.迭代器
__iter__()和__next__()方法 这两个方法是迭代器最基本的方法: 一个用来获得迭代器对象 一个用来获取容器中的下一个元素
>>> a=[1,2,3]
>>> b=iter(a) #迭代器,省内存
>>> b.__next__()
1
>>> b.__next__()
2
>>> b.__next__()
3
>>> b.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
调用迭代器的另一个方法
>>> a=[1,2,3]
>>> b=iter(a)
>>> next(b)
1
>>> next(b)
2
>>> next(b)
3
>>> next(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> try: #捕获异常
... next(b)
... except StopIteration:
... print("没有元素可以使用")
...
没有元素可以使用
>>> a=[1,2,3]
>>> b=iter(a)
>>> next(b)
1
>>> for i in b: #已经取出一个值
... print(i)
...
2
3
>>> print(list(b))
[]
>>> type(b)
<class 'list_iterator'>
2.生成器
协程会使用
L = [x * x for x in range(10)] #推导列表
print(L)
g = (x * x for x in range(10)) #生成器,和推导列表区别是括号
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print("----------------------------")
for n in g:
print(n)
print(type(g)) #生成器
print(next(g)) #多取也会抛异常
"""执行结果:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
<generator object <genexpr> at 0x000001AD98B76CC8>
0
1
4
9
----------------------------
16
25
36
49
64
81
<class 'generator'>
File "D:/demo/hello.py", line 14, in <module>
print(next(g))
StopIteration
"""
>>> def odd():
... print ('step 1')
... yield 1 #yield作用,执行到这里时候会暂停 返回1
... print ('step 2')
... yield 3
... print ('step 3')
... yield 5
...
>>> o=odd()
>>> print(next(o))
step 1
1
>>> print(next(o))
step 2
3
>>> print(next(o))
step 3
5
>>> print(next(o))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
3.枚举
>>> a
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> for id,value in enumerate(a):
... print (id,value)
...
0 a
1 b
2 c
3 d
4 e
5 f
6 g
4.深浅拷贝
浅拷贝:所有的子元素全部都是引用拷贝
深拷贝:不可变类型的子元素是引用拷贝
可变类型的子元素是值拷贝(在内存中生成了一个新的存储地址)
>>> import copy
>>> a=[1,2,3,[4,5]]
>>> b=copy.copy(a) #浅拷贝——》引用拷贝
>>> b
[1, 2, 3, [4, 5]]
>>> id(a)
2462821580424
>>> id(b)
2462821579976
>>> a.append(10) #只拷贝父对象,不拷贝对象的内部子对象
>>> a
[1, 2, 3, [4, 5], 10]
>>> b
[1, 2, 3, [4, 5]]
>>> a[3].append("hello")
>>> a
[1, 2, 3, [4, 5, 'hello'], 10]
>>> b
[1, 2, 3, [4, 5, 'hello']]
>>> id(a[3])
2462821579848
>>> id(b[3])
2462821579848
>>> a=[1,2,3,[4,5]]
>>> b=copy.deepcopy(a) #深拷贝
>>> b
[1, 2, 3, [4, 5]]
>>> id(a)
2462821579848
>>> id(b)
2462821580232
>>> id(a[3]) #拷贝对象及其子对象
2462821579976
>>> id(b[3])
2462821580488
5.通过list实现队列
队列:先被存入的数据,先被取出。多线程、多进程工作时候用的很多。
(类比:排队买电影票)
堆栈:先进后出
(类比:摞盘子)
a=[]
while 1:
value=input("请输入一个数字:")
if value=="exit":
break
a.insert(0,value)
while 1:
if len(a)>0:
value=a.pop()
#pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
print("get value:%s" %value)
else:
break
#encoding=utf-8
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # Terry arrives
queue.append("Graham") # Graham arrives
print (queue.popleft()) # The first to arrive now leaves
print (queue.popleft()) # The second to arrive now leaves
print (queue) # Remaining queue in order of arrival
#写一个三行三列的矩阵,实现其对应位置的数据相加,并返回一个矩阵
import copy
def matrix_add(matrix_a,matrix_b):
if not isinstance(matrix_a,list) or not isinstance(matrix_b,list):
return None
result=copy.deepcopy(matrix_a)
for i in range(len(matrix_a)):
for j in range(len(matrix_a[0])):
result[i][j]+=matrix_b[i][j]
return result
l1=[[1,2,3],[4,5,6],[7,8,9]]
l2=[[7,8,9],[4,5,6],[1,2,3]]
print(matrix_add(l1,l2))