if/else in a list comprehension

后端 未结 11 759
一个人的身影
一个人的身影 2020-11-21 11:44

How can I do the following in Python?

row = [unicode(x.strip()) for x in row if x is not None else \'\']

Essentially:

  1. replace
11条回答
  •  悲&欢浪女
    2020-11-21 12:18

    you can do this

    row = [unicode(x.strip()) if x != None else '' for x in row]
    

    Some Syntax for List comprehension :

    [item if condition else item for item in items]
    [f(item) if condition else value for item in items]
    [item if condition for item in items]
    [value if condition else value1 if condition1 else value2]
    

提交回复
热议问题