## page was renamed from MicroProj/2008-04-05 ##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = 带次数循环 = ##startInc {{{David.D reply-to python-cn@googlegroups.com, to python-cn`CPyUG`华蟒用户组 , date Sat, Apr 5, 2008 at 11:55 AM }}}subject [CPyUG:45975] [http://groups.google.com/group/python-cn/t/8c9cada1f436b9df python的for如何获得当前循环次数?] == 问题 == 初学者问题:python的for如何获得当前循环次数? 我现在是这样做的: {{{ i = 0 for item in data: ... i +=1 }}} 有更好的方法吗? == 解答 == {{{ for i in range(len(data)): data[i]=xxx }}} == 深答 == {{{ >>> for i,v in enumerate(['a','b']): ... print i,v ... 0 a 1 b }}} === enumerate === enumerate:: * [[http://docs.python.org/lib/built-in-funcs.html|内建函式]]! * e.g{{{ >>> v_list_ascii=map(lambda x:chr(x),range(ord('a'),ord('z'))) >>> v_list_ascii ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y'] >>> v_enum=enumerate(v_list_ascii) >>> while True: try: print v_enum.next() except StopIteration: break (0, 'a') (1, 'b') (2, 'c') ...... (23, 'x') (24, 'y') >>> v_enum=enumerate(v_list_ascii) >>> for v_id,v_val in v_enum: print v_id,v_val 0 a 1 b 2 c ...... 23 x 24 y }}} example from[http://tinyurl.com/6rv22s a gift from the gods.] ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]