使用enumerate函数
普通的遍历(打印出 索引+值)
In [5]: seq = ["one", "two", "three"]
In [6]: i = 0
In [7]: for ele in seq:
...: seq[i] = '%d: %s' % (i, seq[i])
...: i += 1
...:
In [8]: print seq
['0: one', '1: two', '2: three']
使用enumerate后
In [9]: seq = ["one", "two", "three"]
In [10]: for i, ele in enumerate(seq):
...: seq[i] = '%d: %s' % (i, seq[i])
...:
In [11]: print seq
['0: one', '1: two', '2: three']
更加pythonic的写法
In [12]: seq = ["one", "two", "three"]
In [13]: print ['%d: %s' % (i, ele) for i, ele in enumerate(seq)]
['0: one', '1: two', '2: three']
哈,函数使得代码更加整洁了呢!(参照网上示例。)
网友评论