if/else in a list comprehension

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

    Make a list from items in an iterable

    It seems best to first generalize all the possible forms rather than giving specific answers to questions. Otherwise, the reader won't know how the answer was determined. Here are a few generalized forms I thought up before I got a headache trying to decide if a final else' clause could be used in the last form.

    [expression1(item)                                        for item in iterable]
    
    [expression1(item) if conditional1                        for item in iterable]
    
    [expression1(item) if conditional1 else expression2(item) for item in iterable]
    
    [expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]
    

    The value of item doesn't need to be used in any of the conditional clauses. A conditional3 can be used as a switch to either add or not add a value to the output list.

    For example, to create a new list that eliminates empty strings or whitespace strings from the original list of strings:

    newlist = [s for s in firstlist if s.strip()]
    

提交回复
热议问题