我创建了一个简单的程序,它使用 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
我想用循环“while”替换if not in s_list
操作并比较这些函数的复杂性。
所以,我编写了以下代码(不起作用):
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
如果您使用 break
,则可以简化此操作,而不是使用 found
变量:
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
关于python - 使用 "while"从另一个列表中删除一个列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41731955/