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

Python使用MTGTools提取万智牌多面卡战力值的语法报错求助

问题说明

我是Python新手,当前问题依赖MTGTools工具包。

背景

万智牌(Magic: The Gathering)是一款集换式卡牌游戏,其中生物类卡牌具有*Power(战力)*属性。
使用MTGTools包下载卡牌数据后,可通过如下语法访问单张卡牌战力值:

PCardList.creatures().cards.data[0].power_num 

PCardList是PCards类型的列表,PCards是“代表万智牌及其特征属性的简易持久化数据类”。
creatures()方法过滤出所有具备战力属性的生物卡牌。
cards.data[0].power_num返回PCardlist中首张生物卡牌的战力数值,power_num是cards.data[0]索引到的PCard对象的属性。
近期官方推出了多面卡牌,每个面的战力值存储在PCard对象的字典属性中,访问卡牌正面战力的语法如下:

PCardList.creatures().cards.data[0].card_faces[0].get('power_num')

单面卡牌的card_faces为NoneType类型,双面卡牌的card_faces是包含2个字典的列表,可通过get('power_num')获取对应面的战力。

问题描述

我需要生成PCardList中所有卡牌的战力列表,如下列表推导式仅对单面卡有效:

[PCardList.creatures().cards.data[i].power_num for i in range(0,len(PCardList.creatures()))]

如果PCardList包含多面卡,会返回类似[1.0, 2.0, None, 1.0, 3.0]的结果。我希望判断PCard是否为多面卡,若是则将每个面的战力作为单独条目加入列表,比如上述示例中如果多面卡正面战力5.0、背面战力0.0,最终列表应为[1.0, 2.0, 5.0, 0.0, 1.0, 3.0]。

尝试方案

我写了如下代码:

pow_list = []
for x in PCardList.creatures().cards.data:
if x.card_faces is None:
    pow_list.append(x.power_num)
else:
    pow_list.append(x.card_faces[0].get('power_num')) #add first face
    pow_list.append(x.card_faces[1].get('power_num')) #add second face

最初if行报语法错误,我将判断条件改为is None、将keys()改为get()后,新报错如下:

pow_list.append(x.card_faces[0].get('power_num')
   ^
SyntaxError: invalid syntax

请问我该如何修复语法问题,实现上述需求?


修复方案

你遇到的两个语法问题分别是缩进错误和括号不匹配:

  1. Python要求循环、条件判断的代码块必须缩进,你写的if语句是for循环内的代码,没有缩进会直接报错
  2. 你报错的那行append方法少写了收尾的右括号)

修复后的可运行代码如下:

pow_list = []
# 提前提取生物列表,避免重复调用creatures()方法提升效率
creature_cards = PCardList.creatures().cards.data
for x in creature_cards:
    if x.card_faces is None:
        # 单面卡直接添加战力
        pow_list.append(x.power_num)
    else:
        # 双面卡分别添加两个面的战力
        pow_list.append(x.card_faces[0].get('power_num'))
        pow_list.append(x.card_faces[1].get('power_num'))

如果你偏好更简洁的写法,也可以用生成器实现:

pow_list = [val for x in PCardList.creatures().cards.data 
           for val in ([x.power_num] if x.card_faces is None 
                     else [x.card_faces[0].get('power_num'), x.card_faces[1].get('power_num')])]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:27:04