A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing) , where thing is either an iterator or a sequence, returns a iterator that will return (0, thing [0]) , (1, thing [1]) , (2, thing [2]) , and so forth. A c
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which sup- ports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and t
在python中处理各类序列时,如果我们想显示出这个序列的元素以及它们的下标,可以使用enumerate()函数. enumerate()函数用于遍历用于遍历序列中的元素以及它们的下标,用法如下: 1.参数为一个元组tuple: for index, value in enumerate(('a', 'b', 'c')): '''下标,元素''' print(index,value) 2..参数为一个列表list: for index, value in enumerate([1, 2, 3])
enumerate函数用于遍历序列中的元素以及它们的下标 i = 0 seq = ['one', 'two', 'three'] for element in seq: print i, seq[i] i += 1 #0 one #1 two #2 three print '============' seq = ['one', 'two', 'three'] for i, element in enumerate(seq): print i, seq[i] print '===========
range()是列表, xrange()是迭代 >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb 然而,在大部分情况下使用enumerate()函数会更加方便,请参见循环的技巧.
enumerate字典上是枚举.列举的意思. C语言中关键字enum也是enumerate的缩写. python中enumerate方法,返回一个enumerate类型.参数一般是可以遍历的的东西,比如列表,字符串什么的. python文档中是这么说的: enumerate(sequence, [start=0]) Return an enumerate object. sequence must be a sequence, an iterator, or some other
zip是一个内置函数, 接受两个或多个序列,并将他们拉到一起,成为一个元组列表.每个元组包含各个序列中的一个元素. s = 'abc' t = [0,1,2] zip(s,t) >>>[('a',0),('b',1),('c',2)] 如果需要遍历序列中的元素以及它们的下标,可以使用内置函数enumerate: for index,elemet in enumerate('abc'): print index,element >>> 0 a 1 b 2 c
在Python2.x中,items( )用于 返回一个字典的拷贝列表[Returns a copy of the list of all items (key/value pairs) in D],占额外的内存. iteritems() 用于返回本身字典列表操作后的迭代[Returns an iterator on all items(key/value pairs) in D],不占用额外的内存. Python 3.x 里面,iteritems() 和 viewitems() 这两个方法都已经