涉及元组和最后元组的范围

2024-09-24 04:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行for来检查元组列表。有点像

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

我要确保temp不会取之前在循环中验证过的元组的值。有什么办法吗?在


Tags: ofin列表forrangetemp元组actual
2条回答

首先是你的代码有问题。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

这是我的两分钱。 注意,这将使temp(1-4)无匹配。在

# 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

相关问题 更多 >