0

5.4.14Python下通过索引编号迭代序列

Posted by 撒得一地 on 2016年4月2日 in python教程

有些时候想要迭代序列中的对象,同时还要获取当前对象的索引。例如,在一个字符串列表中替换索引包含“abc”的字符串。实现的方法有很多,比如可以用下面这种方法:

>>> list = ['abc','abcde','ff','abc']
>>> for string in list:
...     if 'abc' in string:
...             index = list.index(string)
...             list[index] = 'ccc'
...
>>> list
['ccc', 'ccc', 'ff', 'ccc']

上面的例子中,不好的地方在于在替换字符串前还要搜索给定的字符串。还有另一种比较好的方法,如:

>>> list = ['abc','abcde','ff','abc']
>>> index = 0
>>> for string in list:
...     if "abc" in string:
...             list[index] = "ccc"
...     index += 1
...
>>> list
['ccc', 'ccc', 'ff', 'ccc']

另一种方法是使用内建的enumerate函数:

>>> list = ['abc','abcde','ff','abc']
>>> for (index,string) in enumerate(list):
...     if "abc" in string:
...             list[index] = "ccc"
...
>>> list
['ccc', 'ccc', 'ff', 'ccc']

enumerate函数可以在提供索引的地方迭代索引-值(键值)对。

上一篇:

下一篇:

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注

4 + 3 = ?

网站地图|XML地图

Copyright © 2015-2024 技术拉近你我! All rights reserved.
闽ICP备15015576号-1 版权所有©psz.