繁体   English   中英

用 python 中不同长度的子列表替换子列表,如 string.replace

[英]Replace sublist with different-length sublist in python, like string.replace

我正在寻找类似 string.replace 的 function,但对于列表。

例如,使用 string.replace:

>>> s="abcd abcd"
>>> s.replace("bc", "XYZ")
'aXYZd aXYZd'

因此,同一事物的列表版本将是这样的:

>>> l=['a','b','c','d',' ', 'a','b','c','d']
>>> l.replace(['b','c'], ['X','Y','Z'])
['a','X','Y','Z',d,' ','a','X','Y','Z',d]

注意:这不仅仅是用其他东西替换列表中的单个元素。 它用可能具有不同长度的不同子列表替换所有出现的子列表 - 就像 string.replace() 对子字符串所做的那样。

(我实际使用的列表实际上并不是字符列表,因此无法转换为字符串。)

没有在列表中搜索子列表的操作。 但是,一旦您知道位置。 操作简单。

def listfind( haystack, needle ):
  for i in range(len(haystack)-len(needle)):
      if haystack[i:i+len(needle)] == needle:
          return i
  return -1

def listreplace( old, new, haystack ):
    n = listfind( haystack, old )
    if n < 0:
        return haystack
    return haystack[0:n] + new + haystack[n+len(old):]

l=['a','b','c','d',' ', 'a','b','c','d']
l1 = listreplace( ['b','c'], ['X','Y','Z'], l )
print( l1 )

Output:

['a', 'X', 'Y', 'Z', 'd', ' ', 'a', 'b', 'c', 'd']

我试着写在 python


def replaceSubList(myList,listToReplace,listToBeReplacedWith):
    idx=0
    val=True
    while val:
        if myList[idx:].__contains__(listToReplace[0]) and myList.__len__()>=idx+myList[idx:].index(listToReplace[0])+listToReplace.__len__():
            idx=idx+myList[idx:].index(listToReplace[0])
            if listToReplace==myList[idx+myList[idx:].index(listToReplace[0]):idx+myList[idx:].index(listToReplace[0])+listToReplace.__len__()]:
                myList=myList[0:idx]+listToBeReplacedWith+myList[idx+listToReplace.__len__():]
            elif(idx<myList.__len__()):
                idx+=1
            else:
                val=False
        else:
            val=False

    print(myList)

replaceSubList([1,2,3,4,5,6,7,8,4,12,3,4,5,1,2,3,4,5,6,5,4],[4,5], [110,130,170,200]) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM