简体   繁体   中英

Python 'in' operator doesn't work in array

i'm quite a beginner in python and making 2D random walker program.(up & down and left & right). I hope the walker not to go the position where it visited.

So, I made some arrays and one is the array which collect history of coordinate. And I also defined a function which returns possible option at specific position. It seems that the functions doesn't do

def opt(histo,cur):
  tmp=[]
  tmp.append([cur[0]+1,cur[1]])
  tmp.append([cur[0]-1,cur[1]])
  tmp.append([cur[0],cur[1]+1])
  tmp.append([cur[0],cur[1]-1])
  tmp.remove(histo[-2])
  print "current history : ",histo
  print "current tmp : ",tmp
  print "current pos : ",cur
  for i in tmp:
    if i in histo:
      print str(i)+" was detected!!"
      tmp.remove(i)
  return tmp

The code results in

...

current history : [[0, 0], [0, -1], [0, -2], [-1, -2], [-1, -1], [-2, -1], [-2, 0], [-3, 0], [-3, -1], [-3, -2], [-3, -3], [-4, -3], [-5, -3], [-6, -3], [-7, -3], [-7, -2], [-6, -2], [-5, -2], [-5, -1], [-4, -1], [-4, - 2]]

current tmp : [[-3, -2], [-5, -2], [-4, -3]]

current pos : [-4, -2]

[-3, -2] was detected!!

[-4, -3] was detected!!

After elimination : [[-5, -2]]

....

Why [-5,-2] is safe in this case?

The smallest possible change follows:

def opt(histo,cur):
  tmp=[]
  tmp.append([cur[0]+1,cur[1]])
  tmp.append([cur[0]-1,cur[1]])
  tmp.append([cur[0],cur[1]+1])
  tmp.append([cur[0],cur[1]-1])
  tmp.remove(histo[-2])
  print "current history : ",histo
  print "current tmp : ",tmp
  print "current pos : ",cur
  for i in list(tmp):
    if i in histo:
      print str(i)+" was detected!!"
      tmp.remove(i)
  return tmp

That is to say, it changes tmp to list(tmp) . That way, you're not iterating over the same copy of the list that you're modifying.

That said, in is inefficient when used on lists, and tuples should be used for the inner data structure for performance and correctness reasons. So you should also change [cur[0]+1, cur[1]] to (cur[0]+1, cur[1]) for all references, and modify the type of histo to be a set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM