Python多条件列表推导式报错求助:基于均值中位数赋值
问题解答
完全可以在单个列表推导式中实现类似elif的多分支逻辑,不需要改用循环。你的代码报错是因为条件判断的嵌套语法错误,把类型判断的位置放错了。
错误分析
你写的skew行列表推导式,最后一个if any(...)的位置不符合Python语法规则。正确逻辑应该是先判断列是否为数值类型,再根据中位数和均值的关系返回对应结果,否则返回空格。原代码把类型判断放在了最内层的条件分支里,导致语法结构混乱。
修正后的代码
from sklearn.datasets import load_iris bunch = load_iris(as_frame=True) df = bunch.data.reset_index().rename(columns={"index": "id"}).merge(bunch.target.reset_index().rename(columns={"index": "id"})).drop(["id"], axis=1) # 修正后的skew列表推导式 datasummary_dct = { "50%": [df[col].median().round(2) if any(t in str(df[col].dtype) for t in ("float", "int", "time")) else " " for col in df.columns], "mean": [df[col].mean().round(2) if any(t in str(df[col].dtype) for t in ("float", "int", "time")) else " " for col in df.columns], "skew": [ "left" if df[col].median() > df[col].mean() else "right" if df[col].median() < df[col].mean() else "equal" if any(t in str(df[col].dtype) for t in ("float", "int", "time")) else " " for col in df.columns ], }
优化建议(可选)
因为多次重复判断列类型的逻辑,可以把它提取成一个小函数,让代码更清晰易维护:
def is_numeric(col): dtype = str(col.dtype) return any(t in dtype for t in ("float", "int", "time")) datasummary_dct = { "50%": [col.median().round(2) if is_numeric(col) else " " for _, col in df.items()], "mean": [col.mean().round(2) if is_numeric(col) else " " for _, col in df.items()], "skew": [ "left" if col.median() > col.mean() else "right" if col.median() < col.mean() else "equal" if is_numeric(col) else " " for _, col in df.items() ], }
逻辑说明
列表推导式里的多分支判断遵循A if 条件1 else B if 条件2 else C的结构,完全对应普通if-elif-else的逻辑:
- 先判断是否为数值类型,如果不是直接返回
" " - 如果是数值类型,再依次判断中位数和均值的大小关系,返回对应的
"left"/"right"/"equal"
内容的提问来源于stack exchange,提问作者plotmaster473
相关产品推荐
相关产品推荐

