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

如何将指定Python代码改写为一行?能否简化该if-else语句写法?

一行改写与更简洁的条件判断方案

嘿,针对你的问题,我给你整理了几种实用的解决方案:

1. 直接改写成一行代码

如果你确实需要把整个__init__方法压缩成一行,可以用分号分隔语句,结合嵌套三元表达式实现:

def __init__(self, attributes): self.attributes = attributes; self.diabetes = "yes" if "yes" in self.attributes else "no" if "no" in self.attributes else ""

不过要提醒你,这种写法虽然满足了“一行”的要求,但可读性会有所下降,团队协作场景下不太推荐优先使用。

2. 更优雅的if-else替代方案

比起嵌套三元,还有几种既简洁又易读的写法,更适合日常开发:

方案A:利用集合交集快速匹配

通过集合的交集操作,直接定位attributes中是否包含目标值,代码紧凑且逻辑清晰:

def __init__(self, attributes):
    self.attributes = attributes
    matched = {"yes", "no"} & set(attributes)
    self.diabetes = matched.pop() if matched else ""

方案B:生成器表达式 + next()

用生成器遍历目标值,找到第一个存在于attributes中的结果,默认返回空字符串:

def __init__(self, attributes):
    self.attributes = attributes
    self.diabetes = next((val for val in ["yes", "no"] if val in attributes), "")

方案C:简化版三元表达式

如果还是偏好三元表达式的写法,可以调整成更直观的结构,避免嵌套带来的阅读负担:

def __init__(self, attributes):
    self.attributes = attributes
    self.diabetes = "yes" if "yes" in attributes else "no" if "no" in attributes else ""

这些方案都能完美替代原来的if-elif-else结构,代码更简洁的同时也保持了良好的可读性~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:21:56