2008年4月7日星期一

python的非经典错误

def comp_tuple_file (tuple_file1, tuple_file2):
for i in tuple_file1:
if i in tuple_file2:
tuple_file1.remove(i);
tuple_file2.remove(i);
if __name__=="__main__":
t1=[(1,"1"),(2,"2"),(3,"3")];
t2=[(1,"1"),(3,"3"),(2,"2"),(4,"2")];
comp_tuple_file (t1, t2);
print t1;
print t2;
错在哪里?
头一次循环,i=(1,"1")被正确移除了。但是接下来,i=(3,"3")?
这个叠代器的行为很有意思哦,貌似叠代器内存储的是集合的索引。
def comp_tuple_file (tuple_file1, tuple_file2):
collection=tuple_file1[:];
for i in collection:
if i in tuple_file2:
tuple_file1.remove(i);
tuple_file2.remove(i);
if __name__=="__main__":
t1=[(1,"1"),(2,"2"),(3,"3")];
t2=[(1,"1"),(3,"3"),(2,"2"),(4,"2")];
comp_tuple_file (t1, t2);
print t1;
print t2;
这才是正确的代码。

没有评论: