热线电话:13121318867

登录
2018-11-23 阅读量: 796
迭代时获取索引

在有些情况下,你需要在迭代对象序列的同时获取当前对象的索引。例如,你可能想替换一 个字符串列表中所有包含子串'xxx'的字符串。当然,完成这种任务的方法有很多,但这里假设 你要像下面这样做:

for string in strings:

if 'xxx' in string:

index = strings.index(string) # 在字符串列表中查找字符串

strings[index] = '[censored]'

这可行,但替换前的搜索好像没有必要。另外,如果没有替换,搜索返回的索引可能不对(即 返回的是该字符串首次出现处的索引)。下面是一种更佳的解决方案:

index = 0

for string in strings:

if 'xxx' in string:

strings[index] = '[censored]'

index += 1

这个解决方案虽然可以接受,但看起来也有点笨拙。另一种解决方案是使用内置函数 enumerate。

for index, string in enumerate(strings):

if 'xxx' in string:

strings[index] = '[censored]'

这个函数让你能够迭代索引值对,其中的索引是自动提供的。

0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子