迭代器与生成器
列表推导式
#打印30以内能被3整除的数, 放到一个列表里
result = [ i for i in range(30) if i%3 == 0]
print(result)
#30以内能被3整除的数的平方
print([ i*i for i in range(30) if i%3 == 0])
#列表里的浮点数保留两位小数, 整数保持原样
lst = [2.43, 6.666,9, 2.2324]
print( [ round(i,2) for i in lst])
嵌套推导式
print([ i for lst in lst2 for i in lst if i%2 ])
集合推导式
str1 = "asdofiwejfoasidjfowerijf"
print(set(str1))
print({i for i in str1})
字典推导式
str1 = "seofiajweoifksadjfsfss"
result = {i:str1.count(i) for i in str1}
print(result)
print({j:i for i,j in result.items()})
q1 = ['a','ab','abc','abcd','abcde']
print([ i.upper() for i in q1 if len(i) >=3])
print([ (x,y) for x in range(6) if x%2 == 0 for y in range(6) if y%2 == 1])
q4 = {'B':3, 'a':1, 'b':6, 'c':3, 'A':4}
print({i.lower(): q4.get(i.lower(),0) + q4.get(i.upper(),0) for i in q4 })
可迭代对象
实现了 __iter__方法,并且该方法返回一个迭代器,这样子的对象就是可迭代对象
>>> hasattr(a,"__iter__")
True
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> from collections import Iterable
>>> isinstance(a, Iterable)
True
>>> isinstance(1, int)
True
>>> isinstance(a, list)
True
可迭代对象有哪些?
1、容器类型都是可迭代对象
list tuple dict set str
2、range
3、打开的文件
迭代器
任何实现了__iter__()和__next__()都是迭代器
iter() 返回自身
next() 下一个值
for循环中,先调用__iter__获取到一个迭代器
然后再不断的调用__next__ 获取下一个值
for循环中,如果遇到StopIteration,就退出循环
>>> lst = ["a","b","c"]
>>> dir(lst)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> r1 = lst.__iter__()
>>> dir(r1)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__length_hint__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__']
>>> r1.__next__()
'a'
>>> r1.__next__()
'b'
>>> 1.__next__()
File "<stdin>", line 1
1.__next__()
^
SyntaxError: invalid syntax
>>> r1.__next__()
'c'
>>> r1.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> lst
['a', 'b', 'c']
>>> r2 = iter(lst)
>>> r2
<list_iterator object at 0x7f16046e0898>
>>> next(r2)
'a'
>>> next(r2)
'b'
>>> next(r2)
'c'
>>> next(r2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration