迭代器
在python中,迭代器协议就是实现对象的__iter()方法和next()方法,其中前者返回对象本身,后者返回容器的下一个元素。实现了这两个方法的对象就是可迭代对象。迭代器是有惰性的,只有在使用时才会产生,这就为处理大量数据提供了好处,不同一次性把所有数据写入内存。下面自己写了一个迭代器,可以看到使用for循环可以处理自己编写的迭代器,实现了迭代器协议的对象,可以使用任何类似于for循环这样的迭代器工具。但是,看下面的输出,第二次输出为空,这是为什么呢?我们在使用list时,可以多次输出同一个对象,这和实现了自己实现了迭代器协议的对象有什么区别?
class it(object):def __init__(self, n):
self.a = 0
self.n = n
def __iter__(self):
<br/>return self
def next(self):
if self.a < self.n:
self.a += 1
return self.a
else:
raise StopIteration
i=it(5)
for j in i:
print j,
print ''
print '------'
for j in i:
print j
# 1 2 3 4 5
# ------
经过学习,得知,list等类型迭代器返回的是一个迭代器对象,不是返回了本身。那么就写了如下代码进行测试,经过打印输出可以看到,类TestIt的对象是可以反复使用的。那么又有一个问题了,没有实现next()方法的对象,还是迭代器对象吗?这是因为在使用it类时,是返回了迭代器对象的,把迭代的功能使用了it迭代器实现,也就是说相当于实现了迭代器协议。迭代器协议在python中很有用,python中有一个关于迭代器的模块itertools,下面我就学习一下itertools模块,看看有哪些惊喜!
class TestIt(object): def __init__(self, a): self.a = a def __iter__(self): return it(self.a)
itertools
无限迭代器
1 count(),接受两个参数,第一个是开始的数字,第二个是步幅,默认从0开始,用法如下
import itertools as it c = it.count(10, 2) for i in c: if i > 20: break print i, # 10 12 14 16 18 20
2 cycle(),接受一个参数,该参数是迭代器对象(列表,字符串等),会循环生成迭代器中的元素
c = it.cycle([1, 2, 3]) i = 1 for j in c: if i > 7: break print j, i += 1
3 repeat(),接受两个参数,用于生成第一个参数n次
for j in it.repeat([1, 2, 3], 4): print j
有限迭代器,选取感觉自己常用的介绍下
1 chain(),接受多个迭代器对象作为参数,并把它们连接起来chain('abc', [1, 2, 3])
2 compress(data, selectors), 根据后面的参数过滤前面的参数,两个参数都需要是迭代器对象
3 dropwhile(pre, iterable),pre参数是一个函数,当pre(i)是Ture是,返回该项以及后面所有项
4 groupby(iterable[, keyfunc]),其中iterable 是一个可迭代对象,keyfunc 是分组函数,用于对 iterable 的连续项进行分组,如果不指定,则默认对 iterable 中的连续相同项进行分组,返回一个 (key, sub-iterator)
的迭代器。
5 ifilter(function or None, sequence),将 iterable 中 function(item) 为 True 的元素组成一个迭代器返回,如果 function 是 None,则返回 iterable 中所有计算为 True 的项
6 tee(iterable [,n]),tee
用于从 iterable 创建 n 个独立的迭代器,以元组的形式返回,n 的默认值是 2。
for j in it.tee('abc', 4): print list(j)
组合生成器
1 permutations(iterable[, r]),用于生成一个排列,r是生成排列的元素长度,不指定则为默认长度
list(it.permutations( list(it.permutations(, 2
2 combinations(iterable, r), 求序列的组合,其中,r 指定生成组合的元素的长度,是必需的参数
3 combinations_with_replacement(iterable, r),生成的组合包含自身元素
print list(it.combinations_with_replacement('abc', 2)) # [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]
更多python迭代器以及itertools模块相关文章请关注PHP中文网!

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

在Python中,可以通过多种方法连接列表并管理重复元素:1)使用 运算符或extend()方法可以保留所有重复元素;2)转换为集合再转回列表可以去除所有重复元素,但会丢失原有顺序;3)使用循环或列表推导式结合集合可以去除重复元素并保持原有顺序。

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版
中文版,非常好用

Dreamweaver Mac版
视觉化网页开发工具

禅工作室 13.0.1
功能强大的PHP集成开发环境