[英]python modify item in list, save back in list
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
now I get an error现在我得到一个错误
TypeError: list indices must be integers, not str
due to this line list[item] = item
由于这一行list[item] = item
which makes sense!这是有道理的! but I do not know how to put the item back into the list at that same index using python但我不知道如何使用 python 将项目放回同一索引的列表中
what is the syntax for this?这是什么语法? Ideally the for loop can keep track of the index I am currently at理想情况下,for循环可以跟踪我当前所在的索引
You could do this:你可以这样做:
for idx, item in enumerate(list):
if 'foo' in item:
item = replace_all(...)
list[idx] = item
You need to use the enumerate function: python docs您需要使用枚举 function: python 文档
for place, item in enumerate(list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.此外,将单词列表用作变量也是一个坏主意,因为它是 python 中的保留字。
Since you had problems with enumerate, an alternative from the itertools library:由于您遇到枚举问题,因此itertools库中的替代方法:
for place, item in itertools.zip(itertools.count(0), list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
A common idiom to change every element of a list looks like this:更改列表的每个元素的常见习惯用法如下所示:
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
This can be rewritten using enumerate() as:这可以使用 enumerate() 重写为:
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
For Python 3:对于 Python 3:
ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
ListOfStrings[idx] = "bar"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.