开发者

For in range involving tuple and last tuple

开发者 https://www.devze.com 2023-02-05 18:30 出处:网络
im running a for to check a list of tuples. something in the lines of for i in range of b: actual=i temp1=(actual[0]+1,actual[1])

im running a for to check a list of tuples. something in the lines of

for i in range of b:
   actual=i
   temp1=(actual[0]+1,actual[1])
   temp2=(actual[0],actual[1]-1)
   temp3=(actual[0],actual[1]+1)
   temp4=(actual[0]-1,actual[1])

And i want to make s开发者_如何转开发ure the temp's NEVER take the value of the tuple verified on the cycle before. Any idea on how to do this?


First, it seems that there's a problem with your code. range accepts integer input, so if b is an integer, for i in range(b) will give you integers [0, 1, 2, .. , b-1 ] in a list. You can't index into i using [], as you do on the next two lines.

If b is not an integer, but a collection, then you should use something like:

# Assuming b is a collection
for i in range(len(b)):
   actual=b[i]
   temp1=(actual[0]+1,actual[1])
   temp2=(actual[0],actual[1]-1)
   temp3=(actual[0],actual[1]+1)
   temp4=(actual[0]-1,actual[1])

   # Check if this is the first one.  If it is, previous won't exist.
   if i == 0:
       continue

   previous = b[i-1]
   if previous in [ temp1, temp2, temp3, temp4 ]:
       # This is what you want not to happen.  Deal with it somehow.
       pass


Here's my two cents. Note that this will make temp(1-4) None if any match.

# assuming b is a collection
for i in range(len(b)):
    actual=b[i]
    if i!=0:
        prev = b[i-1]
    if i==0:
        prev = [[['something']],[['ridiculous']]] #this is so that the rest of the code works even if index is 0
    if (actual[0]+1,actual[1]) != prev: #if it is not the previous item
        temp1=(actual[0]+1,actual[1]) #assign temp1
    else:
        temp1 = None  #temp1 would otherwise automatically take on the value of (b[i-1][0]+1,b[i-1][1])
    if (actual[0],actual[1]-1) != prev:
        temp2=(actual[0],actual[1]-1)
    else:
        temp2 = None
    if (actual[0],actual[1]+1) != prev:
        temp3=(actual[0],actual[1]+1)
    else:
        temp3 = None
    if (actual[0]-1,actual[1]) != prev:
        temp4=(actual[0]-1,actual[1])
    else:
        temp4 = None
0

精彩评论

暂无评论...
验证码 换一张
取 消