Python .replace()索引用作循环的变量
大家好强> 我是初学者,我找不到答案:Python .replace()索引用作循环的变量,python,replace,Python,Replace,大家好 我是初学者,我找不到答案: one = [" January ", " February ", " March ", " April ", " May ", \ " June ", " July ", " August ", " September ", " October "
one = [" January ", " February ", " March ", " April ", " May ", \
" June ", " July ", " August ", " September ", " October ", \
" November ", " December ", " ", "IPS", "COL", "BRT"]
two = ["/01/", "/02/", "/03/", "/04/", "/05/", "/06/", "/07/", "/08/",\
"/09/", "/10/", "/11/", "/12/", ",", "", "", ""]
a = len(one)
b = len(two)
while a>0:
text = open("database.txt", "r")
text = ''.join([i for i in text]).replace(one[a], two[a])
x = open("new_database.txt","w")
x.writelines(text)
x.close()
a = a - 1
错误是:
text = ''.join([i for i in text]).replace(one[a], two[a])
IndexError: list index out of range
如果有人能帮忙,非常感谢 错误是因为列表索引是从零开始的,因此
one
的有效索引是0
到len(one)-1
。由于您将a
初始化为len(one)
,因此它超出了范围
但是,您不应该手动分配索引变量并减少它们,而应该只循环遍历列表元素。您可以使用zip()
并行循环浏览两个列表
这里有一个更好的写作方法:
with open("database.txt", "r") as indb, open("new_database.txt", "w") as outdb:
for line in indb:
for old, new in zip(one, two):
line = line.replace(old, new)
outdb.write(line)
如果
a
是one
的长度,则a
超出one
的范围,并且one[a]
将导致索引错误。长度a
列表的索引必须严格小于a
。列表索引从0到len-1
。因此,您需要执行a=len(one)-1
除了Khelwood之外,python还从0索引列表。这意味着,当a>=0时,您也应该执行,或者您可以对in范围(len(one)-1,-1,-1)使用:
,每次通过循环,您都要在原始数据库.txt
上执行替换,而不是先前替换的结果。噢,哇!我对编程很不熟悉,但是…很小的一步。谢谢