if/else in a list comprehension

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

    Here is another illustrative example:

    >>> print(", ".join(["ha" if i else "Ha" for i in range(3)]) + "!")
    Ha, ha, ha!
    

    It exploits the fact that if i evaluates to False for 0 and to True for all other values generated by the function range(). Therefore the list comprehension evaluates as follows:

    >>> ["ha" if i else "Ha" for i in range(3)]
    ['Ha', 'ha', 'ha']
    

提交回复
热议问题