Python 对于包含元组和最后一个元组的范围内的
我正在运行一个for来检查元组列表。类似于Python 对于包含元组和最后一个元组的范围内的,python,algorithm,graph,logic,Python,Algorithm,Graph,Logic,我正在运行一个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永远不会接受之前在循环中验证过的元组的值。你知道怎么做吗?首先,你的代码似乎有问题range接受整数输入,因
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永远不会接受之前在循环中验证过的元组的值。你知道怎么做吗?首先,你的代码似乎有问题
range
接受整数输入,因此如果b
是整数,则范围(b)中i的将在列表中为您提供整数[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)为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
你的问题很模糊。如何“验证”元组?请发布此循环所属的代码,因为我不理解您在上一个循环中验证的内容。您担心闭包吗?这就是你的问题吗?