if/else in a list comprehension

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

    # coding=utf-8
    
    def my_function_get_list():
        my_list = [0, 1, 2, 3, 4, 5]
    
        # You may use map() to convert each item in the list to a string, 
        # and then join them to print my_list
    
        print("Affichage de my_list [{0}]".format(', '.join(map(str, my_list))))
    
        return my_list
    
    
    my_result_list = [
       (
           number_in_my_list + 4,  # Condition is False : append number_in_my_list + 4 in my_result_list
           number_in_my_list * 2  # Condition is True : append number_in_my_list * 2 in my_result_list
       )
    
       [number_in_my_list % 2 == 0]  # [Condition] If the number in my list is even
    
       for number_in_my_list in my_function_get_list()  # For each number in my list
    ]
    
    print("Affichage de my_result_list [{0}]".format(', '.join(map(str, my_result_list))))
    

    (venv) $ python list_comp.py
    Affichage de my_list [0, 1, 2, 3, 4, 5]
    Affichage de my_result_list [0, 5, 4, 7, 8, 9]

    So, for you: row = [('', unicode(x.strip()))[x is not None] for x in row]

提交回复
热议问题