Python list comprehension - simple

后端 未结 3 1431
春和景丽
春和景丽 2020-12-10 06:53

I have a list and I want to use a certain function only on those entries of it that fulfills a certain condition - leaving the other entries unmodified.

Example: Say

3条回答
  •  一生所求
    2020-12-10 07:38

    You could use lambda:

    >>> a_list = [1, 2, 3, 4, 5]
    >>> f = lambda x: x%2 and x or x*2
    >>> a_list = [f(i) for i in a_list]
    >>> a_list
    [1, 4, 3, 8, 5]
    

    Edit - Thinking about agf's remark I made a 2nd version of my code:

    >>> a_list = [1, 2, 3, 4, 5]
    >>> f = lambda x: x if x%2 else x*2
    >>> a_list = [f(i) for i in a_list]
    >>> a_list
    [1, 4, 3, 8, 5]
    

提交回复
热议问题