如何在python中替换列表列表中的字符串,但我只想将更改应用于特定的索引,而不影响其他索引,下面是一些示例:
mylist = [["test_one", "test_two"], ["test_one", "test_two"]]我想将单词"test“更改为"my”,这样结果将只影响第二个索引:
mylist = [["test_one", "my_two"], ["test_one", "my_two"]]我知道如何更改两个列表,但如果只更改一个特定的索引,我就不知道该怎么做。
发布于 2020-03-02 11:43:00
使用索引:
newlist = []
for l in mylist:
l[1] = l[1].replace("test", "my")
newlist.append(l)
print(newlist)如果在子列表中总是有两个元素,则可以使用oneliner:
newlist = [[i, j.replace("test", "my")] for i, j in mylist]
print(newlist)输出:
[['test_one', 'my_two'], ['test_one', 'my_two']]发布于 2020-03-02 11:43:15
有一种方法可以在一行代码中做到这一点,但目前还没有出现在我面前。下面是如何在两行代码中完成此操作。
for two_word_list in mylist:
two_word_list[1] = two_word_list.replace("test", "my")https://stackoverflow.com/questions/60482258
复制相似问题