if/else in Python's list comprehension?

How can I do the following in Python?

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

Essentially:

  • replace all the Nones with empty strings, and then
  • carry out a function.

  • You can totally do that, it's just an ordering issue:

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

    Note that this actually uses a different language construct, a conditional expression, which itself is not part of the comprehension syntax, while the if after the for…in is part of list comprehensions and used to filter elements from the source iterable.

    Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the ternary operator ?: that exists in other languages. For example:

    value = 123
    print(value, 'is', 'even' if value % 2 == 0 else 'odd')
    

    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.


    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']
    
    链接地址: http://www.djcxy.com/p/4536.html

    上一篇: Python的英寸

    下一篇: if / else在Python的列表理解?