我试图在列表中找到一个可变大小的切片,并将其替换为一个元素:
ls = ['c', 'b', 'c', 'd', 'c']
lt = ['b', 'c']
r = 'bc'
for s,next_s in zip(ls, ls[1:]):
for t, next_t in zip(lt, lt[1:]):
if (s, next_s) == (t, next_t):
i = ls.index(s)
ii = ls.index(next_s)
del ls[i]
del ls[ii]
ls.insert(i, r)
print (ls)
这有时只能起作用,产生:
['c', 'bc', 'd', 'c']
但如果lt = ['d', 'c']
和r = 'dc'
,则无法生成:
['b', 'c', 'c', 'dc']
如何解决这个问题?或者有什么更好的方法来解决这个问题?
答案 0 :(得分:1)
可能对您有用的简单方法(取决于lt
是否可以多次出现以及该怎么做)。
ls = ['c', 'b', 'c', 'd', 'c']
lt = ['b', 'c']
r = 'bc'
for i in range(len(ls)):
if ls[i:i+len(lt)] == lt:
ls[i:i+len(lt)] = [r]
print(ls)