python修改列表中的项目,保存回列表中 [英] python modify item in list, save back in list

查看:146
本文介绍了python修改列表中的项目,保存回列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种直觉,我需要访问(字符串)列表中的项目,修改该项目(作为字符串),然后将其放回相同索引的列表中

I have a hunch that I need to access an item in a list (of strings), modify that item (as a string), and put it back in the list in the same index

我很难将某项返回到相同的索引

I'm having difficulty getting an item back into the same index

for item in list:
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[item] = item
        print item

现在我得到一个错误

TypeError: list indices must be integers, not str

由于此行list[item] = item

这很有道理!但我不知道如何使用python

which makes sense! but I do not know how to put the item back into the list at that same index using python

这是什么语法?理想情况下,for循环可以跟踪我当前所在的索引

what is the syntax for this? Ideally the for loop can keep track of the index I am currently at

推荐答案

您可以执行以下操作:

for idx, item in enumerate(list):
   if 'foo' in item:
       item = replace_all(...)
       list[idx] = item

这篇关于python修改列表中的项目,保存回列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆