提取元组中的元素
任务:
每个学生的记录用一个 tuple
(元组)表示,里面包含了学生的学号和名字。
举个例子: ('B0094358N', 'Shao Hong')
你需要写一个叫 get_student_name
的函数,当你把学生的学号和学生记录传给这个函数时,它会返回这个学生的名字。如果学号在记录里找不到,就返回字符串 'Not found'
。
- 输入示例:
get_student_name('B2245467C', student_records)
- 输出示例:
'Yang Shun'
请帮我检查一下我的代码:
def get_student_name(matric_num, records):
l = student_records
for i in l:
if matric_num == i[0]:
return (i[1])
elif matric_num != i[0]:
continue
if matric_num not in l:
return ('Not found')
我遇到了硬编码的错误,但我不知道为什么。
2 个回答
0
你的学生记录结构是什么样的还不太清楚。从你的代码来看,猜测它应该是一个元组的列表,所以我们就这样假设吧。
我觉得问题出在你for循环后的if条件上。如果你在for循环中没有返回任何东西,那就意味着在你的学生记录里找不到这个学号。所以你可以试试这样做 -
def get_student_name(matric_num, records):
l = student_records
for i in l:
if matric_num == i[0]:
return (i[1])
elif matric_num != i[0]:
continue
return ('Not found')
或者,稍微更符合Python风格的做法 -
def get_student_name(matric_num, records):
l = student_records
student_name = [i[1] for i in l if i[0] == matric_num]
return student_name if len(student_name) > 0 else "Not found"
1
试试这个简化版。你不需要 else 条件或者 continue
,因为一旦找到匹配的内容,循环就会直接返回。
>>> def get_student_name(matric_num, records):
... for i in records:
... if i[0] == matric_num:
... return i[1]
... return 'Not Found'
...
>>> records = [('123','Jim'),('456','Bob'),('890','Sam')]
>>> get_student_name('999', records)
'Not Found'
>>> get_student_name('123', records)
'Jim'