代码之家  ›  专栏  ›  技术社区  ›  Yaniv K.

Python——根据条件通过迭代修改列表值的最佳方法

  •  0
  • Yaniv K.  · 技术社区  · 8 年前

    假设我有以下清单:

    lst = [1, 2, 3, 4]
    

    我想检查某个值是否符合某个条件,如果是,修改该值。最好的方法是什么?就像是清晰和高效的结合。我想出了以下三种选择:

    # option 1
    for i, item in enumerate(lst):
        if item == 2:
            lst[i] = 7
    
    # option 2
    counter = 0
    for i in lst:
        if i == 2:
            lst[counter] = 7
        counter += 1
    
    # option 3
    for i in range(len(lst)):
        if lst[i] == 2:
            lst[i] = 7
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   user10210717    8 年前

    我建议混合使用列表理解和函数定义:

    lst = [1, 2, 3, 4]
    
    def replace(x,y=2,z=7):
        """Replace value if condition holds. 
    
        Keyword arguments:
        x -- value to check for replacement
        y -- x will be replaced if it has the value of y
        z -- x will be replaced by z if x is equal to y
        """
        if(x==y):
            x=z
        return x
    
    lst = [replace(x,2,7) for x in lst]