【问题标题】:Python string split on possible None valuePython字符串拆分可能的无值
【发布时间】:2013-08-11 14:29:57
【问题描述】:

我正在构建一个 json,我想将一个逗号分隔的列表 ID 拆分为 ID 数组并放入 json。问题是该列表在数据库中也可以为NULL,因此在python中为None

部分代码如下:

'followupsteps': [{
    'id': stepid,
} for stepid in string.split(step.followupsteps, ',') 

我尝试过这样的事情:

'followupsteps': [{
    'id': stepid,
} for stepid in (string.split(step.followupsteps, ',') if not None else [])]

'followupsteps': [{
    'id': stepid,
} for stepid in string.split((step.followupsteps if not None else ''), ',')]

它们都会导致 Django/python 错误: 异常值: 'NoneType' 对象没有属性 'split'

有什么想法吗?

【问题讨论】:

  • 有什么方法可以在循环前检查变量是否为None

标签: python django string split nonetype


【解决方案1】:

您想测试 step.followupsteps 是否为布尔值 true:

'followupsteps': [] if not step.followupsteps else [{
    'id': stepid,
} for stepid in step.followupsteps.split(',')]

您正在测试 not None 是否为 True,它恰好是:

>>> bool(not None)
True

not step.followupsteps 如果是空字符串、None、数字 0 或空容器,则为 True。你也可以使用if step.followupsteps is None,但为什么要限制自己。

另一种拼写方式:

'followupsteps': [{
    'id': stepid,
} for stepid in (step.followupsteps.split(',') if step.followupsteps else [])]

但是通过首先返回一个空列表,您可以完全避免空列表理解。

【讨论】:

  • @JonClements:返回一个包含一个空字符串的列表。你最终得到[{'id': ''}] 而不是[]
【解决方案2】:

您的三元语句扩展为:

if not None:
   step.followupsteps
else:
   ''

not None 总是计算为True,所以这相当于根本不写if/else 语句。

您想编写(thing to evaluate) if step.followupsteps else (default thing),利用None 对象的“虚假性”。或者,如果更方便,(default thing) if not step.followupsteps else (thing to evaluate)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2021-12-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多