代码之家  ›  专栏  ›  技术社区  ›  nigel222

为什么Python列表有扩展方法?[副本]

  •  1
  • nigel222  · 技术社区  · 9 年前

    什么是 a_list.extend(list2) 做(或做得更好)那件事 a_list += list2 不?

    这是真的,除了注意到如果 .extend() 返回了扩展列表,以便可以级联另一个方法。但它没有,所以你不能。

    2 回复  |  直到 9 年前
        1
  •  11
  •   Martijn Pieters    9 年前

    list.extend() 是一个 表示 并且可以嵌入到较大的表达式中。 += 陈述 、和语句永远不能嵌入表达式中。

    所以你可以这样做:

    doubled_extender = lambda l, it: l.extend(v for v in it for _ in range(2))
    

    但你不能用 那里

    list 对象 object.__iadd__() special method 那个 使用, calls list.extend() directly 返回之前 self .

    最后不能不提 the Augmented Assignments feature 添加到语言的时间晚于 列表扩展() .

        2
  •  3
  •   PM 2Ring    9 年前

    另一个好处是 .extend 您可以在全局列表中调用它,因为这只会改变列表,而 += 无法在该上下文中工作,因为您无法在本地范围内分配给全局。

    a_list = ['one']
    list2 = ['two', 'three']
    
    def f():
        a_list.extend(list2)
    
    def g():
        a_list += list2
    
    f()
    print(a_list)
    g()
    print(a_list)
    

    输出

    ['one', 'two', 'three']
    Traceback (most recent call last):
      File "./qtest.py", line 43, in <module>
        g()
      File "./qtest.py", line 39, in g
        a_list += list2
    UnboundLocalError: local variable 'a_list' referenced before assignment
    

    然而,你 可以 使用 += 如果您也使用切片赋值,因为这也是原始列表的变体:

    a_list = ['one']
    list2 = ['two', 'three']
    
    def g():
        a_list[:] += list2
    
    g()
    print(a_list)
    

    输出

    ['one', 'two', 'three']
    
    推荐文章