[英]why this python function skips index 1 to 3 without iterating index 2 when running in a for loop
我编写了一个函数来删除在两个字符串中重复的部分。 我首先将字符串转换为列表并遍历两个列表以查找同一位置上的字符是否相同。 问题是在迭代时,代码跳过索引 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)
迭代的同一个列表上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'])
你可以稍微修改你的代码
def popp(s, t):
s_lis = list(s)
t_lis = list(t)
s_res = []
t_res = []
# match each character. Stops once the
# shortest list ends
for i, j in zip(s_lis, t_lis):
if i != j:
s_res.append(i)
t_res.append(j)
# if s is longer, take rest of the string and
# add it to residual
if len(s) > len(t):
for x in s_lis[len(t):]:
s_res.append(x)
if len(t) > len(s):
for x in t_lis[len(s):]:
t_res.append(x)
print(s_res)
print(t_res)
popp('hackerhappy','hackerrank')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.