首页 > 解决方案 > 解包元组返回错误的结果

问题描述

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

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

标签: pythontuples

解决方案


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

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


推荐阅读