我编写了一个函数来删除两个字符串中重复的部分。我首先将字符串转换为列表,然后迭代两个列表以查找同一位置上的字符是否相同。问题是迭代时, 代码跳过索引 2。(例如:list="index",迭代器在迭代“i”后跳转到“d”)。
我尝试使用“替换”方法进行字符串操作,但没有得到我想要的结果。 “替换”方法删除了我想要的部分。
def popp(s,t):
s_lis=list(s)
t_lis=list(t)
ind=0
for i,j in zip(s_lis,t_lis):
if i==j:
s_lis.pop(ind)
t_lis.pop(ind)
else:ind+=1
return s_lis,t_lis
# test the code
print(popp('hackerhappy','hackerrank'))
expected result: ['h','p','p','y'] ['r','n','k']
actual result: ['k', 'r', 'h', 'a', 'p', 'p', 'y'], ['k', 'r', 'r', 'a', 'n', 'k']
最佳答案
首先,您应该使用 itertools.zip_longest这会从最长的子序列中提取出来。您正在使用 zip
来从最短的子序列中生成 zip,这是您不想要的。
所以在我们的例子中,它将是
print(list(zip_longest(s_lis, t_lis)))
#[('h', 'h'), ('a', 'a'), ('c', 'c'), ('k', 'k'), ('e', 'e'),
#('r', 'r'), ('h', 'r'), ('a', 'a'), ('p', 'n'), ('p', 'k'), ('y', None)]
那么您应该使用另一个列表来附加非常见字符,而不是通过 s_lis.pop(idx)
对您正在迭代的同一个列表进行操作
因此,如果元组中的字符不匹配,则将它们追加(如果不是 None)
from itertools import zip_longest
def popp(s,t):
s_lis = list(s)
t_lis = list(t)
s_res = []
t_res = []
#Use zip_longest to zip the two lists
for i, j in zip_longest(s_lis, t_lis):
#If the characters do not match, and they are not None, append them
#to the list
if i != j:
if i!=None:
s_res.append(i)
if j!=None:
t_res.append(j)
return s_res, t_res
输出将如下所示:
print(popp('hackerhappy','hackerrank'))
#(['h', 'p', 'p', 'y'], ['r', 'n', 'k'])
关于python - 为什么这个Python函数在for循环中运行时跳过索引1到3而不迭代索引2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55769977/