欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python语法官方文档序列类型(list,tuple,range)

程序员文章站 2022-06-13 21:22:05
iterator…迭代器(iterator)是连接容器和算法的纽带,为数据提供了抽象,使写算法的人不必关心各种数据结构的细节。…迭代器模式1.特点:将对集合的访问与遍历从集合对象中分离出来到迭代器中。 2.概念:迭代器模式(Iterator)就是分离了聚合对象的遍历行为,抽象出一个迭代器来负责这样既可以做到不暴露集合的内部结构,又可让外部代码透明的访问集合内部……迭代子(Iterator)迭代子是指针概念的泛型化,它指向容器中的元素,它能象指针一样增减,轮流指示容器中每个元素。…迭代子模式(I...
In [1]: %timeit [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
170 ns ± 5.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [2]: %timeit (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25)
9.44 ns ± 0.231 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

iterator
…迭代器
(iterator)是连接容器和算法的纽带,为数据提供了抽象,使写算法的人不必关心各种数据结构的细节。
…迭代器模式
1.特点:将对集合的访问与遍历从集合对象中分离出来到迭代器中。 2.概念:迭代器模式(Iterator)就是分离了聚合对象的遍历行为,抽象出一个迭代器来负责这样既可以做到不暴露集合的内部结构,又可让外部代码透明的访问集合内部…
…迭代子(Iterator)
迭代子是指针概念的泛型化,它指向容器中的元素,它能象指针一样增减,轮流指示容器中每个元素。
…迭代子模式(Iterator)
供应一种体例依次访谒一个聚合工具中的各个元素,而又不需表露该工具的内部表示。
In object-oriented computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container’s interface.
在面向对象的计算机编程中,迭代器是一种使程序员能够遍历容器(特别是列表)的对象。各种类型的迭代器通常通过容器的接口提供。
container.__iter__()返回一个迭代器对象。该对象需要支持下文所述的迭代器协议。如果容器支持不同的迭代类型,则可以提供额外的方法来专门地请求不同迭代类型的迭代器。(支持多种迭代形式的对象的例子有同时支持广度优先和深度优先遍历的树结构。)此方法对应于Python/C API中Python对象类型结构体的tp_iter槽位。
迭代器对象自身需要支持以下两个方法,它们共同组成了迭代器协议:
iterator._iter__()返回迭代器对象本身。这是同时允许容器和迭代器配合for和in语句使用所必须的。此方法对应于Python/C API中Python对象类型结构体的tp_iter槽位。
iterator.
_next__()从容器中返回下一项。如果已经没有项可返回,则会引发StopIteration异常。此方法对应于Python/C API中Python对象类型结构体的tp_iternext槽位。Python定义了几种迭代器对象以支持对一般和特定序列类型、字典和其他更特别的形式进行迭代。除了迭代器协议的实现,特定类型的其他性质对迭代操作来说都不重要。
一旦迭代器的__next__()方法引发了StopIteration,它必须一直对后续调用引发同样的异常。不遵循此行为特性的实现将无法正常使用。
生成器类型
Python的generator提供了一种实现迭代器协议的便捷方式。如果容器对象__iter__()方法被实现为一个生成器,它将自动返回一个迭代器对象(从技术上说是一个生成器对象),该对象提供__iter__()和__next__()方法。有关生成器的更多信息可以参阅yield表达式的文档。
我的理解是他生成一个迭代器副本,这个副本一般就单纯的是源件的copy,但如果专门定义过__iter__()的话,可以是任意可迭代内容!

序列类型—list,tuple,range

有三种基本序列类型:list, tuple和range对象。
abc: Abstract Base Class 抽象基底类别
抽象类(abstract base class,ABC)就是类里定义了纯虚成员函数的类。纯虚函数一般只提供了接口,并不会做具体实现(虽然可以),实现由它的派生类去重写。抽象类不能被实例化(不能创建对象),通常是作为基类供子类继承,子类中重写虚函数,实现具体的接口。简言之,ABC描述的是至少使用一个纯虚函数的接口,从ABC派生出的类将根据派生类的具体特征,使用常规虚函数来实现这种接口。

help(collections.abc.Sequence)
Help on class Sequence in module collections.abc:

class Sequence(Reversible, Collection)
 |  All the operations on a read-only sequence.
 |
 |  Concrete subclasses must override __new__ or __init__,
 |  __getitem__, and __len__.
 |
 |  Method resolution order:
 |      Sequence
 |      Reversible
 |      Collection
 |      Sized
 |      Iterable
 |      Container
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __contains__(self, value)
 |
 |  __getitem__(self, index)
 |
 |  __iter__(self)
 |
 |  __reversed__(self)
 |
 |  count(self, value)
 |      S.count(value) -> integer -- return number of occurrences of value
 |
 |  index(self, value, start=0, stop=None)
 |      S.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |
 |      Supporting start and stop arguments is optional, but
 |      recommended.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset({'__getitem__', '__len__'})
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from Reversible:
 |
 |  __subclasshook__(C) from abc.ABCMeta
 |      Abstract classes can override this to customize issubclass().
 |
 |      This is invoked early on by abc.ABCMeta.__subclasscheck__().
 |      It should return True, False or NotImplemented.  If it returns
 |      NotImplemented, the normal algorithm is used.  Otherwise, it
 |      overrides the normal algorithm (and the outcome is cached).
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from Sized:
 |
 |  __len__(self)

大多数序列类型,包括可变类型和不可变类型都支持下表中的操作。collections.abc.SequenceABC被提供用来更容易地在自定义序列类型上正确地实现这些操作。

此表按优先级升序列出了序列操作。在表格中,s和t是具有相同类型的序列,n,i,j和k是整数而x是任何满足s所规定的类型和值限制的任意对象。

in和not in操作具有与比较操作相同的优先级。+(拼接)和*(重复)操作具有与对应数值运算相同的优先级。

python语法官方文档序列类型(list,tuple,range)(1)虽然in和not in操作在通常情况下仅被用于简单的成员检测,某些专门化序列(例如str,bytes和bytearray)也使用它们进行子序列检测:

>>>"gg"in"eggs"
True

(2)小于0的n值会被当作0来处理(生成一个与s同类型的空序列)。请注意序列s中的项并不会被拷贝;它们会被多次引用。这一点经常会令Python编程新手感到困扰;例如:

>>>lists=[[]]*3
>>>lists[[], [], []]
>>>lists[0].append(3)
>>>lists[[3], [3], [3]]

具体的原因在于[[]]是一个包含了一个空列表的单元素列表,所以[[]] * 3结果中的三个元素都是对这一个空列表的引用。修改lists中的任何一个元素实际上都是对这一个空列表的修改。你可以用以下方式创建以不同列表为元素的列表:

>>>lists=[[]foriinrange(3)]
>>>lists[0].append(3)
>>>lists[1].append(5)
>>>lists[2].append(7)
>>>lists[[3], [5], [7]]

进一步的解释可以在FAQ条目faq-multidimensional-list中查看。

(3)如果i或j为负值,则索引顺序是相对于序列s的末尾:索引号会被替换为len(s) + i或len(s)+ j。但要注意-0仍然为0。

(4)s从i到j的切片被定义为所有满足i <= k < j的索引号k的项组成的序列。如果i或j大于len(s),则使用len(s)。如果i被省略或为None,则使用0。如果j被省略或为None,则使用len(s)。如果i大于等于j,则切片为空。

(5)s从i到j步长为k的切片被定义为所有满足0 <= n < (j-i)/k的索引号x = i + nk的项组成的序列。换句话说,索引号为i,i+k,i+2k,i+3*k,以此类推,当达到j时停止(但一定不包括j)。当k为正值时,i和j会被减至不大于len(s)。当k为负值时,i和j会被减至不大于len(s) - 1。如果i或j被省略或为None,它们会成为“终止”值(是哪一端的终止值则取决于k的符号)。请注意,k不可为零。如果k为None,则当作1处理。

(6)拼接不可变序列总是会生成新的对象。这意味着通过重复拼接来构建序列的运行时开销将会基于序列总长度的乘方。想要获得线性的运行时开销,你必须改用下列替代方案之一:
•如果拼接str对象,你可以构建一个列表并在最后使用str.join()或是写入一个io.StringIO实例并在结束时获取它的值

•如果拼接bytes对象,你可以类似地使用bytes.join()或io.BytesIO,或者你也可以使用bytearray对象进行原地拼接。bytearray对象是可变的,并且具有高效的重分配机制

a=bytearray(b'axitelu')
b''.join(bytes(chr(i),encoding="utf") for i in a)

•如果拼接tuple对象,请改为扩展list类•对于其它类型,请查看相应的文档

(7)某些序列类型(例如range)仅支持遵循特定模式的项序列,因此并不支持序列拼接或重复。

(8)当x在s中找不到时index会引发ValueError。不是所有实现都支持传入额外参数i和j。这两个参数允许高效地搜索序列的子序列。传入这两个额外参数大致相当于使用s[i:j].index(x),但是不会复制任何数据,并且返回的索引是相对于序列的开头而非切片的开头。

不可变序列类型

不可变序列类型普遍实现而可变序列类型未实现的唯一操作就是对hash()内置函数的支持。
这种支持允许不可变类型,例如tuple实例被用作dict键,以及存储在set和frozenset实例中。

可变序列类型

help(collections.abc.MutableSequence)
Help on class MutableSequence in module collections.abc:

class MutableSequence(Sequence)
 |  All the operations on a read-only sequence.
 |
 |  Concrete subclasses must override __new__ or __init__,
 |  __getitem__, and __len__.
 |
 |  Method resolution order:
 |      MutableSequence
 |      Sequence
 |      Reversible
 |      Collection
 |      Sized
 |      Iterable
 |      Container
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __delitem__(self, index)
 |
 |  __iadd__(self, values)
 |
 |  __setitem__(self, index, value)
 |
 |  append(self, value)
 |      S.append(value) -- append value to the end of the sequence
 |
 |  clear(self)
 |      S.clear() -> None -- remove all items from S
 |
 |  extend(self, values)
 |      S.extend(iterable) -- extend sequence by appending elements from the iterable
 |
 |  insert(self, index, value)
 |      S.insert(index, value) -- insert value before index
 |
 |  pop(self, index=-1)
 |      S.pop([index]) -> item -- remove and return item at index (default last).
 |      Raise IndexError if list is empty or index is out of range.
 |
 |  remove(self, value)
 |      S.remove(value) -- remove first occurrence of value.
 |      Raise ValueError if the value is not present.
 |
 |  reverse(self)
 |      S.reverse() -- reverse *IN PLACE*
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset({'__delitem__', '__getitem__', '__len_...
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from Sequence:
 |
 |  __contains__(self, value)
 |
 |  __getitem__(self, index)
 |
 |  __iter__(self)
 |
 |  __reversed__(self)
 |
 |  count(self, value)
 |      S.count(value) -> integer -- return number of occurrences of value
 |
 |  index(self, value, start=0, stop=None)
 |      S.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |
 |      Supporting start and stop arguments is optional, but
 |      recommended.
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from Reversible:
 |
 |  __subclasshook__(C) from abc.ABCMeta
 |      Abstract classes can override this to customize issubclass().
 |
 |      This is invoked early on by abc.ABCMeta.__subclasscheck__().
 |      It should return True, False or NotImplemented.  If it returns
 |      NotImplemented, the normal algorithm is used.  Otherwise, it
 |      overrides the normal algorithm (and the outcome is cached).
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from Sized:
 |
 |  __len__(self)

表格中的s是可变序列类型的实例,t是任意可迭代对象,而x是符合对s所规定类型与值限制的任何对象(例如,bytearray仅接受满足0 <= x <= 255值限制的整数)。

python语法官方文档序列类型(list,tuple,range)

In [53]: s=[[],[],[]]

In [54]: s*=3

In [55]: s[0]=0

In [56]: s
Out[56]: [0, [], [], [], [], [], [], [], []]

In [57]: s[1]=[1]

In [58]: s
Out[58]: [0, [1], [], [], [], [], [], [], []]

In [59]: s[2].append(2)

In [60]: s
Out[60]: [0, [1], [2], [], [], [2], [], [], [2]]

列表

列表是可变序列,通常用于存放同类项目的集合(其中精确的相似程度将根据应用而变化)。

class list([iterable])
可以用多种方式构建列表:
•使用一对方括号来表示空列表:[]
•使用方括号,其中的项以逗号分隔:[a],[a, b, c]
•使用列表推导式:[x for x in iterable]
•使用类型的构造器:list()或list(iterable)

构造器将构造一个列表,其中的项与iterable中的项具有相同的的值与顺序。iterable可以是序列、支持迭代的容器或其它可迭代对象。如果iterable已经是一个列表,将创建并返回其副本,类似于iterable[:]。例如,list(‘abc’)返回[‘a’, ‘b’, ‘c’]而list( (1, 2, 3) )返回[1, 2, 3]。如果没有给出参数,构造器将创建一个空列表[]。

其它许多操作也会产生列表,包括sorted()内置函数。
列表实现了所有一般和可变序列的操作。列表还额外提供了以下方法:

sort(*,key=None,reverse=False)

此方法会对列表进行原地排序,只使用<来进行各项间比较。异常不会被屏蔽——如果有任何比较操作失败,整个排序操作将失败(而列表可能会处于被部分修改的状态)。
sort()接受两个仅限以关键字形式传入的参数(仅限关键字参数):
key指定带有一个参数的函数,用于从每个列表元素中提取比较键(例如key=str.lower)。对应于列表中每一项的键会被计算一次,然后在整个排序过程中使用。默认值None表示直接对列表项排序而不计算一个单独的键值。
可以使用functools.cmp_to_key()将2.x风格的cmp函数转换为key函数。
reverse为一个布尔值。如果设为True,则每个列表元素将按反向顺序比较进行排序。当顺序大尺寸序列时此方法会原地修改该序列以保证空间经济性。为提醒用户此操作是通过间接影响进行的,它并不会返回排序后的序列(请使用sorted()显示地请求一个新的已排序列表实例)。
sort()方法确保是稳定的。如果一个排序确保不会改变比较结果相等的元素的相对顺序就称其为稳定的—这有利于进行多重排序(例如先按部门、再接薪级排序)。
有关排序示例和简要排序教程,请参阅sortinghowto。
CPython implementation detail:在一个列表被排序期间,尝试改变甚至进行检测也会造成未定义的影响。Python的C实现会在排序期间将列表显示为空,如果发现列表在排序期间被改变将会引发ValueError。

python中列表排序,字典排序,列表中的字典排序

In [1]: s=list("赵钱孙李周吴郑王")

In [2]: s
Out[2]: ['赵', '钱', '孙', '李', '周', '吴', '郑', '王']

In [3]: s.sort()

In [4]: s
Out[4]: ['吴', '周', '孙', '李', '王', '赵', '郑', '钱']

In [9]: for c in s:
   ...:     print(ord(c))
   ...:
   ...:
21556
21608
23385
26446
29579
36213
37073
38065
In [12]: s=[{"no":"01","国":"魏","君":"曹"},{"no":"02","国":"蜀","君":"刘"},{"no":"03","国":"吴","君":"孙"}]

In [13]: s
Out[13]:
[{'no': '01', '国': '魏', '君': '曹'},
 {'no': '02', '国': '蜀', '君': '刘'},
 {'no': '03', '国': '吴', '君': '孙'}]

In [18]: s.sort(key= lambda s:s["no"],reverse=True)

In [19]: s
Out[19]:
[{'no': '03', '国': '吴', '君': '孙'},
 {'no': '02', '国': '蜀', '君': '刘'},
 {'no': '01', '国': '魏', '君': '曹'}]

In [20]: s.sort(key= lambda s:s.__getitem__("no"))

In [21]: s
Out[21]:
[{'no': '01', '国': '魏', '君': '曹'},
 {'no': '02', '国': '蜀', '君': '刘'},
 {'no': '03', '国': '吴', '君': '孙'}]

In [28]: s.sort(key=operator.itemgetter("no"))

In [29]: s
Out[29]:
[{'no': '01', '国': '魏', '君': '曹'},
 {'no': '02', '国': '蜀', '君': '刘'},
 {'no': '03', '国': '吴', '君': '孙'}]

元组

元组是不可变序列,通常用于储存异构数据的多项集(例如由enumerate()内置函数所产生的二元组)。元组也被用于需要同构数据的不可变序列的情况(例如允许存储到set或dict的实例)。

什么是异构数据?

class tuple([iterable])
可以用多种方式构建元组:
•使用一对圆括号来表示空元组:()
•使用一个后缀的逗号来表示单元组:a,或(a,)
•使用以逗号分隔的多个项:a, b, cor(a, b, c)
•使用内置的tuple():tuple()或tuple(iterable)

构造器将构造一个元组,其中的项与iterable中的项具有相同的值与顺序。iterable可以是序列、支持迭代的容器或其他可迭代对象。如果iterable已经是一个元组,会不加改变地将其返回。例如,tuple(‘abc’)返回(‘a’, ‘b’, ‘c’)而tuple( [1, 2, 3] )返回(1, 2, 3)。如果没有给出参数,构造器将创建一个空元组()。

请注意决定生成元组的其实是逗号而不是圆括号。圆括号只是可选的,生成空元组或需要避免语法歧义的情况除外。例如,f(a, b, c)是在调用函数时附带三个参数,而f((a, b, c))则是在调用函数时附带一个三元组。

元组实现了所有一般序列的操作。

对于通过名称访问相比通过索引访问更清晰的异构数据多项集,collections.namedtuple()可能是比简单元组对象更为合适的选择。

enumerate(iterable,start=0)
返回一个枚举对象。iterable必须是一个序列,或iterator,或其他支持迭代的对象。enumerate()返回的迭代器的__next__()方法返回一个元组,里面包含一个计数值(从start开始,默认为0)和通过迭代iterable获得的值。

In [1]: seasons=['Spring','Summer','Fall','Winter']

In [2]: list(enumerate(seasons))
Out[2]: [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

In [3]: list(enumerate(seasons, start=1))
Out[3]: [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

等价于

def enumerate(sequence, start=0):
	n=start
	for elem in sequence:
		yield n, elem
		n+=1


python中yield的用法详解——最简单,最清晰的解释

import pysnooper
@pysnooper.snoop()
def enumerate(sequence, start=0):
	n=start
	for elem in sequence:
		yield n, elem
		n+=1
seasons=['Spring','Summer','Fall','Winter']
print(seasons)
print(enumerate(seasons))
print(list(enumerate(seasons,1)))
print(tuple(enumerate(seasons)))
print(dict(enumerate(seasons)))
print(set(enumerate(seasons)))
C:\Users\jhsxy2005\AppData\Local\Programs\Python\Python38\python.exe "C:/Users/jhsxy2005/PycharmProjects/untitled/20200704 enumerate.py"
Source path:... C:/Users/jhsxy2005/PycharmProjects/untitled/20200704 enumerate.py
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
15:58:07.062880 call         3 def enumerate(sequence, start=0):
15:58:07.063880 line         4 	n=start
New var:....... n = 0
15:58:07.063880 line         5 	for elem in sequence:
New var:....... elem = 'Spring'
15:58:07.063880 line         6 		yield n, elem
15:58:07.063880 return       6 		yield n, elem
Return value:.. (0, 'Spring')
Elapsed time: 00:00:00.001000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 0
Starting var:.. elem = 'Spring'
15:58:07.063880 call         6 		yield n, elem
15:58:07.063880 line         7 		n+=1
Modified var:.. n = 1
15:58:07.063880 line         5 	for elem in sequence:
Modified var:.. elem = 'Summer'
15:58:07.063880 line         6 		yield n, elem
15:58:07.063880 return       6 		yield n, elem
Return value:.. (1, 'Summer')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 1
Starting var:.. elem = 'Summer'
15:58:07.063880 call         6 		yield n, elem
15:58:07.063880 line         7 		n+=1
Modified var:.. n = 2
15:58:07.063880 line         5 	for elem in sequence:
Modified var:.. elem = 'Fall'
15:58:07.063880 line         6 		yield n, elem
15:58:07.063880 return       6 		yield n, elem
Return value:.. (2, 'Fall')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 2
Starting var:.. elem = 'Fall'
15:58:07.063880 call         6 		yield n, elem
15:58:07.063880 line         7 		n+=1
Modified var:.. n = 3
15:58:07.063880 line         5 	for elem in sequence:
Modified var:.. elem = 'Winter'
15:58:07.063880 line         6 		yield n, elem
15:58:07.063880 return       6 		yield n, elem
Return value:.. (3, 'Winter')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 3
Starting var:.. elem = 'Winter'
15:58:07.063880 call         6 		yield n, elem
15:58:07.063880 line         7 		n+=1
Modified var:.. n = 4
15:58:07.063880 line         5 	for elem in sequence:
15:58:07.063880 return       5 	for elem in sequence:
Return value:.. None
Elapsed time: 00:00:00.000996
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
15:58:07.064876 call         3 def enumerate(sequence, start=0):
15:58:07.064876 line         4 	n=start
New var:....... n = 0
15:58:07.064876 line         5 	for elem in sequence:
New var:....... elem = 'Spring'
15:58:07.064876 line         6 		yield n, elem
15:58:07.064876 return       6 		yield n, elem
Return value:.. (0, 'Spring')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 0
Starting var:.. elem = 'Spring'
15:58:07.064876 call         6 		yield n, elem
15:58:07.064876 line         7 		n+=1
Modified var:.. n = 1
15:58:07.064876 line         5 	for elem in sequence:
Modified var:.. elem = 'Summer'
15:58:07.064876 line         6 		yield n, elem
15:58:07.064876 return       6 		yield n, elem
Return value:.. (1, 'Summer')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 1
Starting var:.. elem = 'Summer'
15:58:07.064876 call         6 		yield n, elem
15:58:07.064876 line         7 		n+=1
Modified var:.. n = 2
15:58:07.064876 line         5 	for elem in sequence:
Modified var:.. elem = 'Fall'
15:58:07.064876 line         6 		yield n, elem
15:58:07.064876 return       6 		yield n, elem
Return value:.. (2, 'Fall')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 2
Starting var:.. elem = 'Fall'
15:58:07.064876 call         6 		yield n, elem
15:58:07.068876 line         7 		n+=1
Modified var:.. n = 3
15:58:07.068876 line         5 	for elem in sequence:
Modified var:.. elem = 'Winter'
15:58:07.068876 line         6 		yield n, elem
15:58:07.068876 return       6 		yield n, elem
Return value:.. (3, 'Winter')
Elapsed time: 00:00:00.004000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 3
Starting var:.. elem = 'Winter'
15:58:07.068876 call         6 		yield n, elem
15:58:07.068876 line         7 		n+=1
Modified var:.. n = 4
15:58:07.068876 line         5 	for elem in sequence:
15:58:07.068876 return       5 	for elem in sequence:
Return value:.. None
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
15:58:07.068876 call         3 def enumerate(sequence, start=0):
15:58:07.069875 line         4 	n=start
New var:....... n = 0
15:58:07.069875 line         5 	for elem in sequence:
New var:....... elem = 'Spring'
15:58:07.069875 line         6 		yield n, elem
15:58:07.069875 return       6 		yield n, elem
Return value:.. (0, 'Spring')
Elapsed time: 00:00:00.000999
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 0
Starting var:.. elem = 'Spring'
15:58:07.069875 call         6 		yield n, elem
15:58:07.069875 line         7 		n+=1
Modified var:.. n = 1
15:58:07.069875 line         5 	for elem in sequence:
Modified var:.. elem = 'Summer'
15:58:07.069875 line         6 		yield n, elem
15:58:07.069875 return       6 		yield n, elem
Return value:.. (1, 'Summer')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 1
Starting var:.. elem = 'Summer'
15:58:07.069875 call         6 		yield n, elem
15:58:07.069875 line         7 		n+=1
Modified var:.. n = 2
15:58:07.069875 line         5 	for elem in sequence:
Modified var:.. elem = 'Fall'
15:58:07.069875 line         6 		yield n, elem
15:58:07.069875 return       6 		yield n, elem
Return value:.. (2, 'Fall')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 2
Starting var:.. elem = 'Fall'
15:58:07.069875 call         6 		yield n, elem
15:58:07.069875 line         7 		n+=1
Modified var:.. n = 3
15:58:07.069875 line         5 	for elem in sequence:
Modified var:.. elem = 'Winter'
15:58:07.069875 line         6 		yield n, elem
15:58:07.070873 return       6 		yield n, elem
Return value:.. (3, 'Winter')
Elapsed time: 00:00:00.000998
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 3
Starting var:.. elem = 'Winter'
15:58:07.070873 call         6 		yield n, elem
15:58:07.070873 line         7 		n+=1
Modified var:.. n = 4
15:58:07.070873 line         5 	for elem in sequence:
15:58:07.070873 return       5 	for elem in sequence:
Return value:.. None
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
15:58:07.070873 call         3 def enumerate(sequence, start=0):
15:58:07.070873 line         4 	n=start
New var:....... n = 0
15:58:07.070873 line         5 	for elem in sequence:
New var:....... elem = 'Spring'
15:58:07.070873 line         6 		yield n, elem
15:58:07.070873 return       6 		yield n, elem
Return value:.. (0, 'Spring')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 0
Starting var:.. elem = 'Spring'
15:58:07.070873 call         6 		yield n, elem
15:58:07.071873 line         7 		n+=1
Modified var:.. n = 1
15:58:07.071873 line         5 	for elem in sequence:
Modified var:.. elem = 'Summer'
15:58:07.071873 line         6 		yield n, elem
15:58:07.071873 return       6 		yield n, elem
Return value:.. (1, 'Summer')
Elapsed time: 00:00:00.001000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 1
Starting var:.. elem = 'Summer'
15:58:07.071873 call         6 		yield n, elem
15:58:07.071873 line         7 		n+=1
Modified var:.. n = 2
15:58:07.071873 line         5 	for elem in sequence:
Modified var:.. elem = 'Fall'
15:58:07.071873 line         6 		yield n, elem
15:58:07.071873 return       6 		yield n, elem
Return value:.. (2, 'Fall')
Elapsed time: 00:00:00.000000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 2
Starting var:.. elem = 'Fall'
15:58:07.071873 call         6 		yield n, elem
15:58:07.071873 line         7 		n+=1
Modified var:.. n = 3
15:58:07.071873 line         5 	for elem in sequence:
Modified var:.. elem = 'Winter'
15:58:07.072873 line         6 		yield n, elem
15:58:07.072873 return       6 		yield n, elem
Return value:.. (3, 'Winter')
Elapsed time: 00:00:00.001000
Starting var:.. sequence = ['Spring', 'Summer', 'Fall', 'Winter']
Starting var:.. start = 0
Starting var:.. n = 3
Starting var:.. elem = 'Winter'
15:58:07.072873 call         6 		yield n, elem
15:58:07.072873 line         7 		n+=1
Modified var:.. n = 4
15:58:07.072873 line         5 	for elem in sequence:
15:58:07.072873 return       5 	for elem in sequence:
Return value:.. None
Elapsed time: 00:00:00.000000
['Spring', 'Summer', 'Fall', 'Winter']
<generator object enumerate at 0x000002BEA3BD7970>
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
((0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter'))
{0: 'Spring', 1: 'Summer', 2: 'Fall', 3: 'Winter'}
{(0, 'Spring'), (3, 'Winter'), (2, 'Fall'), (1, 'Summer')}

进程已结束,退出代码0

yield可以理解为是专为迭代器的制作的return,return的结果不会直接给函数调用,而是存储起来变成另一个迭代器。
一直到下一次循环不再有yield并且循环结束。
所以一般print的只是一个指针,只能利用list转化后,输出其迭代的结果!

def echo(value=None):
     print("Execution starts when 'next()' is called for the first time.")
     try:
         while True:
             try:
                 value = (yield value)
             except Exception as e:
                 value = e
     finally:
         print("Don't forget to clean up when 'close()' is called.")

generator = echo(1)

print("\n1:\n")
print(next(generator))
print("\n2:\n")
print(next(generator))
print("\n3:\n")
print(next(generator))
print("\n4:\n")
print(generator.send(666))
print("\n6:\n")
print(generator.throw(TypeError, "spam"))
generator.close() #尝试把他注释掉看看
print(next(generator))
input()
1:

Execution starts when 'next()' is called for the first time.
1

2:

None

3:

None

4:

666

6:

spam
Don't forget to clean up when 'close()' is called.

yield赋值给这个函数特殊的定义,符合迭代器的条件,以上代码只不过是描述他的内涵,使用时大概就是赋值给他一个迭代器,他经过一串的运算,返回一个迭代器。
上面代码中使用的是while True,代表着他不会自己结束,于是我没一次次的给他塞参数,强制让他运行。
注意我给的注释。后面几句都是我照抄文档的,中间加的几句是我尝试的,如果没有添加.close(),这个迭代运算就不会结束,但如果侦测到主程序结束,将要关闭,他会自动运行.close()。就像按流程关机一样,系统会挨个的关闭程序,如果程序文件未保存,他会提示并等待。

是否忘记为什么要说到yield了!?

enumerate(iterable,start=0)

collections.namedtuple(typename,field_names,*,rename=False,defaults=None,module=None)

In [4]: from collections import *

In [5]: Point=namedtuple('Point', ['x','y'])

In [6]: p=Point(11,22)

In [7]: p.x
Out[7]: 11

In [8]: p.y
Out[8]: 22

In [9]: p[0]
Out[9]: 11

In [10]: p[1]
Out[10]: 22

In [11]: p
Out[11]: Point(x=11, y=22)

In [12]: a,b=p

In [13]: a
Out[13]: 11

In [14]: t=1,2,3

In [15]: t
Out[15]: (1, 2, 3)

range对象

range类型表示不可变的数字序列,通常用于在for循环中循环指定的次数。
class range(stop)
class range(start,stop[,step])
range构造器的参数必须为整数(可以是内置的int或任何实现了__index__特殊方法的对象)。如果省略step参数,其默认值为1。如果省略start参数,其默认值为0,如果step为零则会引发ValueError。
如果step为正值,确定ranger内容的公式为r[i] = start + stepi其中i >= 0且r[i]< stop。
如果step为负值,确定range内容的公式仍然为r[i] = start + step
i,但限制条件改为i>= 0且r[i] > stop.
如果r[0]不符合值的限制条件,则该range对象为空。range对象确实支持负索引,但是会将其解读为从正索引所确定的序列的末尾开始索引。
元素绝对值大于sys.maxsize的range对象是被允许的,但某些特性(例如len())可能引发OverflowError。

>>>list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>list(range(0,30,5))
[0, 5, 10, 15, 20, 25]
>>>list(range(0,10,3))
[0, 3, 6, 9]
>>>list(range(0,-10,-1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>>list(range(0))
[]
>>>list(range(1,0))
[]

这里和str[::]等index很像,但是不同的是,他的-1是真正的-1
而index的-1是最后一位,所以index想要无损排序,start是“”,即便是“0”,也无法算入i[0]

range对象实现了一般序列的所有操作,但拼接和重复除外(这是由于range对象只能表示符合严格模式的序列,而重复和拼接通常都会违反这样的模式)。
start形参的值(如果该形参未提供则为0)
stop形参的值
step形参的值(如果该形参未提供则为1)
range类型相比常规list或tuple的优势在于一个range对象总是占用固定数量的(较小)内存,不论其所表示的范围有多大(因为它只保存了start,stop和step值,并会根据需要计算具体单项或子范围的值)。
range对象实现了collections.abc.SequenceABC,提供如包含检测、元素索引查找、切片等特性,并支持负索引(参见序列类型— list, tuple, range):

>>>r=range(0,20,2)
>>>r
range(0, 20, 2)
>>>11 in r
False
>>>10 in r
True
>>>r.index(10)
5
>>>r[5]
10
>>>r[:5]
range(0, 10, 2)
>>>r[-1]
18 

使用==和!=检测range对象是否相等是将其作为序列来比较。也就是说,如果两个range对象表示相同的值序列就认为它们是相等的。(请注意比较结果相等的两个range对象可能会具有不同的start,stop和step属性,例如range(0) == range(2, 1, 3)而range(0, 3, 2) == range(0, 4, 2)。)

In [23]: r
Out[23]: range(0, 20, 2)

In [24]: t=0,2,4,6,8,10,12,14,16,18

In [25]: r==t
Out[25]: False

In [26]: tuple(r)==t
Out[26]: True

In [27]: range(t)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-f3c21c917e56> in <module>
----> 1 range(t)

TypeError: 'tuple' object cannot be interpreted as an integer

In [36]: range(t[-1])
Out[36]: range(0, 18)

range()无法迭代赋值,但是可以用一个结果是int的表达式赋值

本文地址:https://blog.csdn.net/jhsxy2005/article/details/107092892