给定下面一段过滤列表的代码
def filterKeyList(key_list, src_list):
for key in key_list:
#print(key)
src_list = filter(lambda x: key in x, src_list)
return src_list
src_list = ['what are you nong', 'what are you nong sha lie ', 'your what name please', 'what?ou are']
key_list = ['what', 'are', 'you']
src_list = filterKeyList(key_list, src_list)
for s in src_list:
print(s)
运行后结果:
从运行结果显然是不符合预期的,最后一个没有包含what are you字符的也返回了。
这是什么情况?
通过文档我们看到,python2与python3的filter返回值类型是不一样的。
python3 filter返回的是迭代器,这样在下次进行filter的时候,src_list就变成了迭代器,需要转为list之后才能进行下一次的filter,从而得到预期的结果。