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

Python中NBA球员数据查询过滤失效问题求助

NBA球员查询功能过滤失效问题排查

问题核心原因

你的代码存在两个关键错误导致过滤完全失效:

  1. 输入未存储:'topic' == input(...)是无意义的比较操作,没有把用户输入的内容保存到变量里,后续过滤根本没用到用户的实际输入。
  2. 过滤逻辑错误:
    • 过滤时用了字符串常量"topic"而非变量,相当于在找姓名等于"topic"的球员,自然没有匹配结果;
    • 连续两次使用filter,要求球员的名和姓同时等于同一个值,逻辑上不可能匹配任何真实球员(比如勒布朗·詹姆斯的名是勒布朗,姓是詹姆斯,不可能同时等于同一个输入)。

修正后的代码

from requests import get
from pprint import PrettyPrinter

BASE_URL = "https://data.nba.net"
ALL_JSON = "/prod/v1/today.json"

printer = PrettyPrinter()

def get_links():
    data = get(BASE_URL + ALL_JSON).json()
    return data['links']

def ask_player():
    players_link = get_links()['leagueRosterPlayers']
    all_players = get(BASE_URL + players_link).json()['league']['standard']
    
    # 保存用户输入的全名并去除首尾空格
    player_full_name = input('Type the player you wish to know more about:').strip()
    # 拆分输入为名字和姓氏,兼容姓氏带空格的情况
    first_name, last_name = player_full_name.split(maxsplit=1)
    
    # 一次完成名和姓的匹配过滤
    matched_players = [
        player for player in all_players
        if player['firstName'] == first_name and player['lastName'] == last_name
    ]
    
    if not matched_players:
        print("No player found with that name.")
        return
    
    for player in matched_players:
        name = player['firstName']
        surname = player['lastName']
        jersey = player['jersey']
        college = player['collegeName']
        dob = player['dateOfBirthUTC']
        years_pro = player['yearsPro']

        printer.pprint(
            f"{name} {surname}, jersey number {jersey}, went to {college} college, "
            f"was born in {dob}, and has been in the NBA for {years_pro} full year(s)."
        )

ask_player()

额外优化说明

  • 用列表推导式替代两次filter,逻辑更清晰且执行效率更高;
  • 添加无匹配时的提示,避免用户因无输出误以为程序故障;
  • 拆分输入时用maxsplit=1,兼容姓氏包含空格的特殊情况;
  • 变量名更语义化,提升代码可读性。

内容的提问来源于stack exchange,提问作者Noisee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:30:49