繁体   English   中英

如何在 Python 中向生成器循环添加条件?

[英]How to add condition to generator loop in Python?

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

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)

你可能想要:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM