if/else in a list comprehension

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

    The other solutions are great for a single if / else construct. However, ternary statements within list comprehensions are arguably difficult to read.

    Using a function aids readability, but such a solution is difficult to extend or adapt in a workflow where the mapping is an input. A dictionary can alleviate these concerns:

    row = [None, 'This', 'is', 'a', 'filler', 'test', 'string', None]
    
    d = {None: '', 'filler': 'manipulated'}
    
    res = [d.get(x, x) for x in row]
    
    print(res)
    
    ['', 'This', 'is', 'a', 'manipulated', 'test', 'string', '']
    

提交回复
热议问题