简体   繁体   中英

How to add condition to generator loop in Python?

Let's say I have a 'line_item' object with values x, y, and z. If I used the following code:

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

And let's say there's a specific issue which sometimes occurs in 'z', where I want to cast it to a string if it's not a string. What would be the syntax for that be? I'm imagining something like...

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

You probably want:

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

However, you can also check if the thing returned is the correct type (a str in your case):

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

Further, you can just always have it cast to a str, if that is the required type. Casting a str to a str is okay.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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