python - 解包元组返回错误的结果
问题描述
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)
orNone
然后检查结果是否为None
.
推荐阅读
- vue.js - 如何在 vue 3-rc.3 中的 .vue 文件中使用 HAML
- ruby-on-rails - 运行 rspec request spec 找不到存在的记录
- java - java.security.cert.CertPathValidatorException:Web 服务调用时出现证书链接错误
- php - HTML mail class name changes
- r - R -- lapply() Functions Not Creating a Readable Output
- r - readr and write_csv: double precision numbers and grisu3
- html - 如何在带有液体变量的html中使用填充突出显示文本
- makefile - 多依赖makefile目标
- python - 使用 UPDATE 时如何防止 SQL 数据库被锁定?
- django - 自动完成 Django 表单 jQuery