if/else in a list comprehension

后端 未结 11 760
一个人的身影
一个人的身影 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:12

    One way:

    def change(f):
        if f is None:
            return unicode(f.strip())
        else:
            return ''
    
    row = [change(x) for x in row]
    

    Although then you have:

    row = map(change, row)
    

    Or you can use a lambda inline.

提交回复
热议问题