检查元组中的元素 insde 元组
Checking elements insde tuples in a tuple
所以基本上我对此很害怕,因为我想检查主元组中的所有元组是否有任何负数,如果有,我希望函数为 return False,如果有不是我想要 return 是的。问题是它只检查第二个元组的第一个元素,我无法弄清楚代码到底出了什么问题。所以如果有人能帮助我,我将不胜感激。
maze = ((1,3),(4,-1))
def lab2(maze):
for i in range(len(maze)):
for y in maze[i+1]:
if maze[i][y] < 0:
return False
else:
return True
print(lab2(maze))
顺便说一句,我忘了说我还想检查是否有重复的元组,如果有我想让函数 return false,但它不起作用
maze = ((1,2),(3,4),(3,4))
def eh_conj_posicoes(maze):
for row in maze:
for el in row:
if el < 0:
return False
tup = ()
for row2 in maze:
tup = tup + maze[0]
if row2[1:] is tup:
return False
else:
tup = tup + row2
return True
print(eh_conj_posicoes(maze))
代码有很多错误,但阻止您进一步研究的问题是当您从一个函数 return 时,该函数将不会继续。因此,如果您想检查数据结构中的所有元素,并且如果其中任何一个为负数则 return False,只有在检查完所有元素后才 return True。现在,只有一个元素被检查,函数 returns 并且不会继续。
def lab2(maze):
for row in maze:
for el in row:
if el < 0:
return False
# Now all for loops have completed
# without returning False (i.e. no negative nubmer)
# So, now we can return True
return True
所以基本上我对此很害怕,因为我想检查主元组中的所有元组是否有任何负数,如果有,我希望函数为 return False,如果有不是我想要 return 是的。问题是它只检查第二个元组的第一个元素,我无法弄清楚代码到底出了什么问题。所以如果有人能帮助我,我将不胜感激。
maze = ((1,3),(4,-1))
def lab2(maze):
for i in range(len(maze)):
for y in maze[i+1]:
if maze[i][y] < 0:
return False
else:
return True
print(lab2(maze))
顺便说一句,我忘了说我还想检查是否有重复的元组,如果有我想让函数 return false,但它不起作用
maze = ((1,2),(3,4),(3,4))
def eh_conj_posicoes(maze):
for row in maze:
for el in row:
if el < 0:
return False
tup = ()
for row2 in maze:
tup = tup + maze[0]
if row2[1:] is tup:
return False
else:
tup = tup + row2
return True
print(eh_conj_posicoes(maze))
代码有很多错误,但阻止您进一步研究的问题是当您从一个函数 return 时,该函数将不会继续。因此,如果您想检查数据结构中的所有元素,并且如果其中任何一个为负数则 return False,只有在检查完所有元素后才 return True。现在,只有一个元素被检查,函数 returns 并且不会继续。
def lab2(maze):
for row in maze:
for el in row:
if el < 0:
return False
# Now all for loops have completed
# without returning False (i.e. no negative nubmer)
# So, now we can return True
return True