【问题标题】:How to add condition to generator loop in Python?如何在 Python 中向生成器循环添加条件?
【发布时间】:2021-04-02 20:40:41
【问题描述】:

假设我有一个值为 x、y 和 z 的“line_item”对象。如果我使用以下代码:

columns_to_write = [
    "x",
    "y",
    "z",
]
params = (line_item.get(col) for col in columns_to_write)

假设在“z”中有时会出现一个特定问题,如果它不是字符串,我想将其转换为字符串。那将是什么语法?我在想像……

params = (if col == "z" then str(line_item.get(col)) else line_item.get(col) for col in columns_to_write)

【问题讨论】:

  • 有什么关系?如果你将一个字符串转换为一个字符串,那么它仍然是一个字符串,所以只需始终转换
  • 这能回答你的问题吗? if/else in a list comprehension

标签: python loops syntax generator


【解决方案1】:

你可能想要:

params = (str(line_item.get(col)) if col == "z" else line_item.get(col) for col in columns_to_write)

但是,您也可以检查返回的东西是否是正确的类型(在您的情况下是 str):

params = (line_item.get(col) if type(col) == str else str(line_item.get(col)) for col in columns_to_write)

此外,您可以始终将其强制转换为 str,如果这是所需的类型。将 str 转换为 str 是可以的。

params = map(lambda x: str(line_item.get(x)), columns_to_write)

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 2017-01-02
    • 2013-02-12
    • 1970-01-01
    • 2022-01-16
    • 2019-12-06
    • 2012-01-27
    • 1970-01-01
    相关资源
    最近更新 更多