gpt4 book ai didi

python - 将指定文本从索引替换为数组python中的另一个索引

转载 作者:太空宇宙 更新时间:2023-11-04 08:26:26 24 4
gpt4 key购买 nike

我想将数组中的搜索文本从指定元素替换为该数组中的另一个指定元素。我知道有一个“替换”功能,但它会替换该搜索字段的所有匹配项。所以我想知道是否有其他功能或其他技巧可以做我想做的事像这样:

myarray = ["time (1)",
"the text to replace ",
"time (2)",
"the text to replace ",
"time (3)",
"the text to replace ",
"time (4)",
"the text to replace ",
"time (5)",
"the text to replace ",
"time (6)",
"the text to replace ",
"time (7)",
"the text to replace ",
"time (8)",
"the text to replace ",
"time (9)",
"the text to replace ",
"time (10)",
"the text to replace "]

myfunc(4,8)

def myfunc(fromtime, totime):
for line in myarray
#find the time from (fromtime) to (totime) and replace 'text' with 'string' for example
print myarray

谁能帮帮我?请!谢谢!

最佳答案

您可以查找 time (4)time(8) 的索引,但是使用那里的 myarray.index()包含在这些限制中的字符串的更改

myarray = ["time (1)","the text to replace ","time (2)","the text to replace ","time (3)","the text to replace ","time (4)","the text to replace ","time (5)","the text to replace ","time (6)","the text to replace ","time (7)","the text to replace ","time (8)","the text to replace ","time (9)","the text to replace ","time (10)","the text to replace "] 

def myfunc(myarray, fromtime, totime):
original_string , replace_string = 'text', 'string'
start_index = myarray.index("time ({})".format(fromtime))
end_index = myarray.index("time ({})".format(totime)) + 2 # + 2 because you want to also change value for the outbound limit
myarray[start_index : end_index] = [value if idx%2 == 0 else value.replace(original_string, replace_string) for idx, value in enumerate(myarray[start_index : end_index]) ]
return myarray

myfunc(myarray, 4,8)

输出

['time (1)',
'the text to replace ',
'time (2)',
'the text to replace ',
'time (3)',
'the text to replace ',
'time (4)',
'the string to replace ',
'time (5)',
'the string to replace ',
'time (6)',
'the string to replace ',
'time (7)',
'the string to replace ',
'time (8)',
'the string to replace ',
'time (9)',
'the text to replace ',
'time (10)',
'the text to replace ']

关于python - 将指定文本从索引替换为数组python中的另一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com