You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用函数实现分数筛选与对应姓名输出的问题求解

Fixing Your Python Function to Match Names with Scores Above 40

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 uses i as an index (0-3), so checking i in get_marks is 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's keys() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 21:12:27