迭代的意思(能源迭代的意思)

怎么真正掌握Python技术?迭代器知识有哪些详解?作为人工智能时代的最佳编程语言,Python凭借入门简单、功能强大的优势吸引了很多人加入学习。对于零基础或者想要快速提升技能的人来说,参加专业学习是一个非常有效的方式,接下来小编给大家分享Python进阶中迭代器的知识。

 

迭代是访问集合元素的一种方式,迭代器是一个可以记住遍历的位置的对象。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束,迭代器只能往前不会后退。

迭代是Python中最强有力的特性之一,可迭代对象包括两种:一类是集合数据类型,如list、tuple、dict、set、str等;一类是generator,包括生成器和带yield的generator function。

可以直接作用于for循环的对象统称为可迭代对象:Iterable。可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。把list、dict、str等Iterable变成Iterator可以使用iter()函数,代码如下:

from collections import Iterable

a=[1,2,4,6,8,6,10]

a=iter(a)

print(next(a))

print(next(a))

print(next(a))

如何判断是否可以迭代?你可以使用isinstance()判断一个对象是否是Iterable对象,代码如下:

from collections import Iterable

print(isinstance([], Iterable))

print(isinstance({}, Iterable))

print(isinstance(‘123’,Iterable))

print(isinstance((x for x in range(5)),Iterable))

print(isinstance(100,Iterable))

Python迭代器的经典用法

1、并行迭代

程序可以同时迭代两个序列。比如有下面两个列表:

names = [‘anne’, ‘beth’, ‘george’, ‘damon’]

ages = [12, 45, 32, 102]

如果想要打印名字和对应的年龄,可以像下面这样做:

In [7]: for i in range(len(names)):

…: print(names[i], ‘is’, ages[i], ‘years old’)

…:

anne is 12 years old

beth is 45 years old

george is 32 years old

damon is 102 years old

这里i是循环索引的标准变量名。而内建的zip函数就可以用来进行并行迭代,可以把两个序列 “压缩” 在一起,然后返回一个元组的列表:

>>> zip(names, ages)

[(‘anne’, 12), (‘beth’, 45), (‘george’, 32), (‘damon’, 102)]

现在我可以在循环中解包元组:

In [9]: for name, age in zip(names, ages):

…: print(name, ‘is’, age, ‘years old’)

…:

anne is 12 years old

beth is 45 years old

george is 32 years old

damon is 102 years old

zip函数也可以作用于任意多的序列。关于它很重要的一点是zip可以处理不等长的序列,当最短的序列“用完”的时候就会停止:

>>> zip(range(5), xrange(1000000000))

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

在上面的代码中,不推荐用range替换xrange——尽管只需要要前5个数字,但range会计算所有的数字,这里要花费很长的时间。而使用xrange就没有这个问题,它只计算前5个数字。

2、按索引迭代

有些时间想要迭代访问序列中的对象,同时还有获取当前对象的索引。例如,在一个字符串列表中替换所有包含’xxx’的子字符串。实现的方法肯定有很多,假设你想象下面这样做:

for string in strings:

if ‘xxx’ in string:

index = strings.index(string) # Search for the string in the list of strings

strings[index] = ‘[censored]’

如果不替换的话,搜索还会返回错误的索引(前面出现的同一个词的索引)。一个比较好的版本如下:

index = 0

for string in strings:

if ‘xxx’ in string:

strings[index] = ‘[censored]’

index += 1

另一种方法是使用内建的enumerate函数:

for index, string in enumerate(strings):

if ‘xxx’ in string:

strings[index] = ‘[censored]’

这个函数可以在提供索引的地方迭代索引-值对。

3、翻转和排序迭代

涉及两个有用的函数:reversed和sorted。它们同列表的reverse和sort(sorted和sort使用同样的参数)方法类似,但作用于任何序列或可迭代对象上,不是原地修改对象,而是返回翻转或排序后的版本:

>>> sorted([4, 3, 6, 8, 3])

[3, 3, 4, 6, 8]

>>> sorted(‘Hello, world!’)

[‘ ‘, ‘!’, ‘,’, ‘H’, ‘d’, ‘e’, ‘l’, ‘l’, ‘l’, ‘o’, ‘o’, ‘r’, ‘w’]

>>> list(reversed(‘Hello, world!’))

[‘!’, ‘d’, ‘l’, ‘r’, ‘o’, ‘w’, ‘ ‘, ‘,’, ‘o’, ‘l’, ‘l’, ‘e’, ‘H’]

>>> ”.join(reversed(‘Hello, world!’))

‘!dlrow ,olleH’

注意,虽然sorted方法返回列表,reversed方法却返回一个更加不可思议的可迭代对象。它们具体的含义不用过多关注,大可在for循环以及join方法中使用,而不会有任何问题。不过却不能直接对它使用索引、分片以及调用list方法,如果希望进行上述处理,那么可以使用list类型转换返回的对象。

4、迭代器规则

迭代的意思是重复做一些事很多次,就像在循环中做的那样。到现在为止只在for循环中对序列和字典进行过迭代,但实际上也能对其他对象进行迭代:只要改对象实现了__iter__方法。__iter__方法会返回一个迭代器(iterator),所谓的迭代器就是具有next方法(这个方法在调用时不需要任何参数)的对象。在调用next方法时,迭代器会返回它的下一个值。如果next方法被调用,但迭代器没有值可以返回,就会引发一个StopIteration异常。

只要大家真正掌握了Python技术,胜任以上岗位就不是难题。如果你想快速学习Python技术,那就赶快加入到专业的学习吧。

本文来自互联网,版权归原作者所有。如若转载,请注明出处:https://www.yishidian.com/cy/21365.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注


Warning: error_log(/www/wwwroot/www.yishidian.com/cy/wp-content/plugins/spider-analyser/#log/log-1808.txt): failed to open stream: No such file or directory in /www/wwwroot/www.yishidian.com/cy/wp-content/plugins/spider-analyser/spider.class.php on line 2900