美文网首页
python函数巧用之---enumerate

python函数巧用之---enumerate

作者: ikaroskun | 来源:发表于2017-03-14 19:43 被阅读23次

使用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']

哈,函数使得代码更加整洁了呢!(参照网上示例。)

相关文章

网友评论

      本文标题:python函数巧用之---enumerate

      本文链接:https://www.haomeiwen.com/subject/eytknttx.html