【发布时间】:2016-04-09 21:43:18
【问题描述】:
我有以下代码:
a= ['hello','how','are','hello','you']
b= ['hello','how','you','today']
len_b=len(b)
for word in a:
count=0
while count < len_b:
if word == b[count]:
a.remove(word)
break
else:
count=count+1
print a
目标是它基本上输出(列表a的内容)-(列表b的内容) 所以在这种情况下想要的结果是 a = ['are','hello']
但是当我运行我的代码时,我得到 a= ['how','are','you']
谁能指出我的实现有什么问题,或者有没有更好的方法来解决这个问题?
【问题讨论】:
-
在迭代列表时不要更改列表的长度。此外,除非订单相关,否则您可以只使用
print set(a) - set(b)。
标签: python string list loops sorting