zoukankan      html  css  js  c++  java
  • python3学习笔记--list.append()/extend()/+=

    list插入一个元素时

    a=[1,2,3]
    a.append(2)
    a+=[2]
    a.extend([2])

    以上三种方法等价; list结尾处插入list中的元素时:

    >>>a=[1,2,3]
    >>>a.extend(a)
    >>>a
    [1,2,3,1,2,3]
    >>>a+=a
    >>>a
    [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
    >>>a=[1,2,3]
    >>>a.append(a)
    >>>a
    [1, 2, 3, [...]]
    >>>a[-1]==a
    True

    +=和extend相当于把列表的元素加入到列表的结尾。

    list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

    append相当于把list插入到原有list的结尾处,造成对自己的引用,形成了无限循环。

    list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].

  • 相关阅读:
    性能优化
    几种跨域处理
    重温前端基础之-数组去重
    移动端常遇到的问题
    WPF 应用
    WPF 应用
    WPF 应用
    C# 应用
    WPF 应用
    C# 应用
  • 原文地址:https://www.cnblogs.com/straight/p/7718139.html
Copyright © 2011-2022 走看看