python-3.x 删除列表中的每两个匹配项

m4pnthwp  于 2023-05-30  发布在  Python
关注(0)|答案(2)|浏览(211)

我最近在做一些python,如果有人可以帮助,我想了这个练习:
删除s中每两次出现(即,第2次、第4次、第6次等)的术语。上面的代码不起作用,我试图打印出aabcdaxyaa112

def delete_occurence(s, term):
    s = [s[i:i + 2] for i in range(0, len(s), 2)]
    s_length = len(s)
 
    for item in range(1, s_length):
        if (s[item] == term) and (item % 2 == 0):
            s.remove(s[item])
    print(''.join(s))
            

delete_occurence("aabcdaaaxyaa11aa2", "aa")
e0bqpujr

e0bqpujr1#

你的代码不能工作,因为很多事情:

  • remove只删除字符串的第一个匹配项
  • 当你移走一些东西的时候索引就会移动

我的方法是根据术语拆分字符串,然后重新创建列表元素,在2次中只插入一次术语。并处理最后一个元素的角情况。

def delete_occurence(s, term):
    # split string, get rid of "term" strings
    toks = s.split(term)
    rval = []
    # loop on the split list of strings
    for i,t in enumerate(toks):
        # add string
        rval.append(t)
        if i%2==0 and i!=len(toks)-1:
            # add term only if not last item and if i is even
            rval.append(term)
    # recreate the string from the list
    return "".join(rval)

# prints aabcdaxyaa112
print(delete_occurence("aabcdaaaxyaa11aa2", "aa"))
ffx8fchx

ffx8fchx2#

我觉得一种方法是简单地用正则表达式找到你有 * term* 的索引。然后把绳子的这些部分去掉。请注意,如果您在同一个字符串上强制执行效果(例如下面的代码),则需要保留一个偏移量,以了解 term 索引的更新值。

import re

def delete_occurence(s, term):
    indices = [m.start() for m in re.finditer(term, s)]
    indices_odd = indices[1::2]

    offset = 0
    for indice in indices_odd:
        indice -= offset
        s = s[:indice] + s[indice + len(term):]
        offset += len(term)

    print(s)
  
delete_occurence("aabcdaaaxyaa11aa2", "aa")

相关问题