Python中使用函数实现分数筛选与对应姓名输出的问题求解
Hey there! Let's sort out your code and get the result you're looking for. First, let's break down where your current implementation is going off track, then build a clean, working function step by step.
What's Wrong with Your Current Code?
Let's go through the issues one by one:
- When you use
filter(lambda x:x>40,tmarks), you get a list of scores (50, 75) — but your loop usesias an index (0-3), so checkingi in get_marksis comparing an index number to a score, which will never be true. - The condition
if i in get_marks==i in zipper.values()is both syntactically and logically incorrect. This isn't how you check if a score meets your threshold. zipper.keys(i)is invalid syntax: a dictionary'skeys()method doesn't take arguments. You can't retrieve a key by passing a value this way.
Simple, Correct Implementations
You don't even need to convert to a dictionary to solve this — here are two straightforward approaches:
Approach 1: Iterate with Indexes
If you want to stick with using indexes, you can loop through the length of the tuples and check each score directly:
def print_students_above_40(names, marks): for idx in range(len(marks)): if marks[idx] > 40: print(names[idx]) # Test the function names = ('John','Sharon','Jack','Annie') marks = (32,50,75,12) print_students_above_40(names, marks)
Approach 2: Use zip to Pair Names and Scores (Cleaner!)
The zip() function was made for exactly this scenario — it pairs elements from multiple iterables together. This lets you loop through names and scores directly, no indexes needed:
def print_students_above_40(names, marks): for name, mark in zip(names, marks): if mark > 40: print(name) # Test the function names = ('John','Sharon','Jack','Annie') marks = (32,50,75,12) print_students_above_40(names, marks)
If You Want to Use a Dictionary (Like Your Original Idea)
If you still want to use a dictionary to store student-score pairs, you can loop through the dictionary's items:
def print_students_above_40(names, marks): student_scores = dict(zip(names, marks)) for name, score in student_scores.items(): if score > 40: print(name) # Test the function names = ('John','Sharon','Jack','Annie') marks = (32,50,75,12) print_students_above_40(names, marks)
All three approaches will output:
Sharon Jack
That's exactly what you're looking for!
内容的提问来源于stack exchange,提问作者Shieldbreaker

