我创建了一个简单的程序,使用in
方法至少两次将一个列表的元素从另一个列表中删除:
def remove(l_list,s_list):
"""Removes items of s_list from l_list and returns the rest"""
res=[]
for item in l_list:
if item not in s_list:
res.append(item)
return res
我想用if not in s_list
“ while”循环代替操作,并比较这些功能的复杂性。
所以,我做了下面的代码(不起作用):
def remove2(l_list,s_list):
res=[]
for item in l_list:
found=False
i=0
while len(s_list)>i and not found:
if item==s_list[i]:
found=True
if not found:
res.append(item)
i+=1
return res
例子:
>>> remove2([1,2,3],[1,2])
[3]
>>> remove2([1,2,3],[1])
[2,3]
我究竟做错了什么?我的逻辑有什么问题?
您应该在while循环之后附加项目:
def remove2(l_list,s_list):
res=[]
for item in l_list:
found=False
i=0
while len(s_list)>i and not found:
if item==s_list[i]:
found=True
i+=1
if not found:
res.append(item)
return res
而不是使用的found
变量,如果你使用,你可以简化这个break
:
def remove2(l_list,s_list):
res=[]
for item in l_list:
i=0
while len(s_list)>i:
if item==s_list[i]:
break
i+=1
else:
# this else belongs to the while loop and is executed if and only if
# the loop wasn't terminated by "break".
res.append(item)
return res
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句