目录python
迭代的对象express
凡是有_iter_方法的对象,都是可迭代对象app
可迭代对象:python内置str,list.,tuple,dict,set,file函数
可迭代对象执行__iter__方法获得返回值,而且可迭代对象会有一个__next__方法。code
s='hello' iter_s = s._iter_() while true: try: print(iter_s__next__()) except stoplteration: break
h e l l o
迭代器对象:执行可迭代对象__iter__方法,拿到返回值就是迭代器对象。对象
特色:ip
1,内置__next__方法,执行该方法会拿到迭代器对象中的一个值内存
2,内置__iter__方法,执行该方法会拿到迭代器自己generator
3,文件自己就是迭代器本iey身it
缺点:
1,取指麻烦只能一个一个取,值取了就没了
2,没法使用len()方法获取长度
for循环称为迭代器循环,in后必须是可迭代对象
由于迭代器使用__iter__
后仍是迭代器自己,所以for循环不用考虑in后的对象是可迭代对象仍是迭代器对象。
因为对可迭代对象使用__iter__
方法后变成一个迭代器对象,这个迭代器对象只是占用了一小块内存空间,他只有使用__next__
后才会吐出一个一个值。如lis = [1,2,3,4,5,...]
至关于一个一个鸡蛋,而lis = [1,2,3,4,5,...].__iter__
至关于一只老母鸡,若是你须要蛋,只须要__next__
便可。
条件成立的返回值if条件else不成立时的返回值
x = 10 y = 20 print(f'x if x>y else y:{x if x>y else y}')
x if x>y else y:20
[expression for item1 in iterable1 if condition1 for item2 in iterable2 if condition2 ... for itemN in iterableN if conditionN ] 相似于 res=[] for item1 in iterable1: if condition1: for item2 in iterable2: if condition2 ... for itemN in iterableN: if conditionN: res.append(expression)
print(F"[i for i in range(10)]: {[i for i in range(10)]}") [i for i in range(10)]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(F"[i**2 for i in range(10)]: {[i**2 for i in range(10)]}") [i**2 for i in range(10)]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print({i:i**2 for i in range(10)})
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
keys = ['name', 'age', 'gender'] values = ['nick', 19, 'male'] res = zip(keys, values) print(F"zip(keys,values): {zip(keys,values)}") info_dict = {k: v for k, v in res} print(f"info_dict: {info_dict}")
zip(keys,values): <zip object at 0x11074c088> info_dict: {'name': 'nick', 'age': 19, 'sex': 'male'}
yield的英文单词意思是生产,在函数中但凡出现yield关键字,再调用函数,就不会继续执行函数体代码,而是会返回一个值。
def func(): print(1) yield print(2) g = func() print(g)
<generator object func at 0x10ddb6b48>
yield:
yield和return:
# 列表推导式 with open('52.txt', 'r', encoding='utf8') as f: nums = [len(line) for line in f] print(max(nums))
# 生成器表达式 with open('52.txt','r',encoding='utf8') as f: nums = (len(line) for line in f) print(max(nums)) # ValueError: I/O operation on closed file.