解压缩元组返回错误的结果


def search(T, num):
**#TODO: Your code goes here
for j in range(len(T)):
if num==T[j]:
found=True
i=j
else:
found=False
i="None"
return found,i
pass**
T = (257, 462, 18, 369, 415, 994, 541, 752, 78, 895, 0, 576, 40, 552, 438, 605, 54, 296, 433, 986, 685, 651, 523, 855, 777, 437, 65, 360, 265, 858, 260, 819, 586, 358, 860, 250, 531, 7, 801, 259, 155, 376, 374, 828, 475, 62, 52, 184, 186, 283, 643, 86, 472, 267, 692, 750, 948, 683, 452, 770, 322, 492, 871, 360, 88, 883, 764, 288, 383, 411, 679, 90, 857, 802, 974, 403, 798, 990, 475, 260, 289, 438, 873, 779, 895, 939, 462, 469, 183, 520, 366, 267, 896, 732, 303, 754, 195, 949, 546, 180)
x = int(input("Enter a number to search for in T: "))
# unpacking returned tuple
found, i = search(T, x)
print(found,i)
if found:
print("First instance found at index {:}".format(i))
else:
print("{} was not found in T".format(x))

----------
Enter a number to search for in T: 777
False None
777 was not found in T

我寻找一个元组中确实存在的数字,为什么它仍然返回未找到? 你能帮我看看待办事项部分吗?

def search(tup, num):
if num in tup:
return True, tup.index(num)
else:
return False, None

注意 您实际上不需要返回元组,只需返回tup.index(num)None,然后检查结果是否None

我假设这是一个编码教程,因为有一个内置函数来做到这一点?

代码中的问题是,当你找到匹配项时,你并没有脱离循环,所以除非匹配项在最后的位置,否则你不会看到它,因为下一个else语句将覆盖你的答案。按如下方式修改循环:

for j in range(len(T)):
if num==T[j]:
return True,j
return False, "None" # or better still the keyword None (no quotes)

找到后,返回foundi。您正在迭代整个元组。 这就是问题所在。

根据您的情况,如果您在搜索中给出元组中的最后一个元素,您将获得预期的结果。

最新更新