涉及元组和最后一个元组的范围循环

0 投票
2 回答
2390 浏览
提问于 2025-04-16 10:09

我正在用一个循环来检查一组元组,类似于下面的代码:

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])

我想确保在每次循环中,临时变量的值永远不会和上一个循环中检查的元组相同。有没有什么办法可以做到这一点?

2 个回答

0

这是我个人的一点看法。请注意,如果有任何匹配的情况,temp(1-4) 的值会变成 None。

# 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

首先,你的代码似乎有点问题。range 这个函数只接受整数作为输入,所以如果 b 是一个整数,for i in range(b) 会给你一个包含整数的列表,内容是 [0, 1, 2, .. , b-1 ]。你不能像接下来的两行那样用 [] 来索引 i

如果 b 不是整数,而是一个集合(比如列表或字典),那么你应该使用类似下面的方式:

# 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

撰写回答