[英]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.