Python list comprehension - simple

后端 未结 3 1432
春和景丽
春和景丽 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:31

    a_list = [1, 2, 3, 4, 5]
    
    print [elem*2 if elem%2==0 else elem  for elem in a_list ]  
    

    or, if you have a very long list that you want to modify in place:

    a_list = [1, 2, 3, 4, 5]
    
    for i,elem in enumerate(a_list):
        if elem%2==0:
            a_list[i] = elem*2
    

    so, only the even elements are modified

提交回复
热议问题