您的位置:首页 > 编程语言 > Python开发

python基础-迭代器、for底层机制、生成器、list结合yield、__call__、yield函数列表

2017-11-03 13:29 811 查看
迭代器概念

for底层机制

生成器
最简单的生成器

返回列表字典元组等

返回多个值构成元组

返回一个函数列表
list结合yield

_call_
多个yield形式

迭代器概念

可迭代的必须含有一个iter方法(可迭代协议)

迭代器比可迭代对象多一个next方法

包含next方法的可迭代对象就是迭代器

迭代器:包含next,iter方法的就是迭代器(迭代器协议)

迭代器是可迭代的一部分

#爬虫作业

#获取列表的方法
print(dir(["safly"]))
#拿到迭代器
print("abc".__iter__())

#依次取值
ite = "abc".__iter__()
print(ite.__next__())
print(ite.__next__())
print(ite.__next__())

#可迭代对象、迭代器
print("------")
l = ["a"]
print(dir(l))
print(dir(l.__iter__()))
#多3个方法
#{'__length_hint__', '__next__', '__setstate__'}
print(set(dir(l.__iter__()))- set(dir(l)))

#1、如何判断是否是可迭代对象或者迭代器?
print("__iter__" in dir('sss'))
print("__next__" in dir("sss"))

#2、如何判断是否是可迭代对象或者迭代器?
from collections import  Iterable
from collections import  Iterator
print(isinstance("a",int))
print(isinstance("a",Iterable))

str_  = "abc".__iter__()
print(isinstance(str_,Iterator))


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/1103.py
['__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']
<str_iterator object at 0x02EC1690>
a
b
c
------
['__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']
['__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__']
{'__setstate__', '__length_hint__', '__next__'}
True
False
False
True
True

Process finished with exit code 0


for底层机制

li = [1,3,4,5]
it = li.__iter__()
while True:
try:
print(it.__next__())
except StopIteration:
break


输出如下:

1
3
4
5


生成器

生成器的本质就是迭代器

只不过是我们自己写的python代码

生成器2种方式

1、生成器函数

2、生成器表达式

生成器函数,调用不执行,而是返回一个生成器,是一个迭代器

[b]最简单的生成器[/b]

def g_func():
print("---g_func---")
yield 1

g = g_func()
print(g)
print(g.__next__())


输出如下:

<generator object g_func at 0x03006540>
---g_func---
1


返回了一个值1

[b]返回列表,字典,元组等[/b]

def g_func():
print("---g_func---")
yield [1,2,3]

g = g_func()
print(g)
print(g.__next__())


输出如下:

<generator object g_func at 0x02A862A0>
---g_func---
[1, 2, 3]


我们看下是返回了一个列表[1, 2, 3]

[b]返回多个值,构成元组[/b]

def cloth(a):
print("aaaa")
cloth = a
yield "第{}件衣服".format(cloth),"yyyyy"

g = cloth(100)
h = g.__next__()
print(h)
print("------")
print(type(h))
print("------")
for i in h:
print(i)


输出如下:

aaaa
('第100件衣服', 'yyyyy')
------
<class 'tuple'>
------
第100件衣服
yyyyy


返回一个函数列表

def yie():
def a():
print("--a")
def b():
print("--b")

yield [a,b]

yie = yie()
next = yie.__next__()
print(next)

next[0].__call__()
next[0]()

next[1].__call__()
next[1]()

print("------------")

def a():
print('调用')

x = a
x.__call__()
x()


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/1104.py
[<function yie.<locals>.a at 0x009BD660>, <function yie.<locals>.b at 0x00B028E8>]
--a
--a
--b
--b
------------
调用
调用

Process finished with exit code 0


[b]list结合yield[/b]

def aaa():
yield 1,2
yield (3,4)
yield {"a":"b"}
yield "saf"
yield 1
yield True

y = list(aaa())
print(y)

y = aaa()
print(y.__next__())
print(y.__next__())
print(y.__next__())
print(y.__next__())
print(y.__next__())
print(y.__next__())


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/1104.py
[(1, 2), (3, 4), {'a': 'b'}, 'saf', 1, True]
(1, 2)
(3, 4)
{'a': 'b'}
saf
1
True

Process finished with exit code 0


_call_

def a():
print("--a")

def b():
print("--b")

lis = [a,b]

ite = lis.__iter__()
ite.__next__().__call__()
ite.__next__().__call__()


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/1104.py
--a
--b

Process finished with exit code 0


[b]多个yield形式[/b]

def g_func():
print("---g_func1---")
yield [1,2]

print("---g_func2---")
print("---g_func3---")
yield [3,4]
print("---g_func4---")

g = g_func()
print(g)
print(g.__next__())
print(g.__next__())


输出如下:

<generator object g_func at 0x039E62A0>
---g_func1---
[1, 2]
---g_func2---
---g_func3---
[3, 4]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: