码迷,mamicode.com
首页 > 其他好文 > 详细

Mutation and Iteration

时间:2017-12-04 19:15:24      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:eve   ges   change   def   nal   rem   and   list   new   

  • avoid mutating a list as you are iterating over it

代码:

def remove_dups(L1,L2):
for e in L1:
if e in L2:
L1.remove(e)

L1=[1,2,4,5]
L2=[2,3,1,6]
remove_dups(L1,L2)

L1

》[2, 4, 5]

L2
》[2, 3, 1, 6]

L1 is [2,4,5], not [4,5] why?
Python uses an internal counter to keep track of index it is in the loop
mutating changes the list length but Python doesn‘t update the counter
loop never sees element 2

所以上述代码是有问题的,可改为:
def remove_dups_new(L1,L2):
  L1_copy = L1[:]
  for e in L1_copy:
    if e in L2:
      L1.remove(e)

Mutation and Iteration

标签:eve   ges   change   def   nal   rem   and   list   new   

原文地址:http://www.cnblogs.com/Bella2017/p/7978053.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!