2 回答
TA贡献1784条经验 获得超9个赞
字符串在python中是不可变的,您应该将串联的结果分配回一个变量:
text[a[l]] = text[a[l]]+text[b[m]]
输出:
['A', '123', 'BCR', 'EFRTY', 'RTY', 'B', '123', 'VCR', 'EF', 'B', '123', 'RRR', 'EFRTY', 'RTY']
TA贡献1765条经验 获得超5个赞
要加入所有相邻'EF','RTY'在列表中不重叠的对:
L = ['A','123','BCR','EF','RTY','B','123','VCR','EF','B','123','RRR','EF','RTY']
result = []
pairs = iter(zip(L, L[1:]+['']))
for a, b in pairs:
if a == 'EF' and b == 'RTY': # found adjacent
a += b # join
next(pairs, None) # skip the next a ('RTY')
result.append(a)
L[:] = result # modify inplace
# -> ['A','123','BCR','EFRTY','B','123','VCR','EF','B','123','RRR','EFRTY']
支持两个以上的单词:
seq = ["EF", "RTY", "B"]
pos = i = 0
while i < len(L):
if L[i:i+len(seq)] == seq:
L[pos] = "".join(seq)
i += len(seq)
else:
L[pos] = L[i]
i += 1
pos += 1
del L[pos:]
添加回答
举报