Python——列表的操作

列表的操作:详细+易出错
假设有两个列表:
    list1 = [1,2,3]
    list2 = ['a','b','c']列表的操作:


1.list.append()
    append只接受一个参数
    append只能在列表的尾部添加元素,不能选择位置添加元素。
      以下操作可以看出
    >>> list1 = [1,2,3]
    >>> list1.append(4)
    >>> list1
    [1, 2, 3, 4]
    >>> list2 = ['a','b','c']
    >>> list2.append(d)        //添加字符串要加‘’
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    NameError: name 'd' is not defined
    >>> list2.append('d')
    >>> list2
    ['a', 'b', 'c', 'd']


2.list.extend()
    extend()方法接受一个列表作为参数,并将该参数的每个元素都添加到原有的列表的尾部。
    若用extend()添加元素,则需要要元素的类型是否于原列表相同,不是很好用,若是需要添加元素,用append更好。
    >>> list1.extend(list2)
    >>> list1
    [1, 2, 3, 4, 'a', 'b', 'c', 'd']
    >>> list2 = ['a','b','c']
    >>> list1 = [1,2,3]
    >>> list1.extend('a')
    >>> list1
    [1, 2, 3, 'a']
    >>> list2.extend(1)        //无法添加数字,数字为int
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not iterable
    >>> list2.extend('1')        //可以添加字符串
    >>> list2
    ['a', 'b', 'c', '1']
    >>> list2.extend(int(1))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not iterable
    >>> list2 = ['a','b','c']
    >>> list2.append(1)
    >>> list2
    ['a', 'b', 'c', 1]


3.list.insert()
    insert()接受两个参数,insert(插入位置,插入元素) 插入位置是从0开始,插入的元素在第i个的前面。insert(i,x)i从0开始,元素x插入在i的前面。
    >>> num = [0,1,2,3]
    >>> num.insert(0,'a')    //插入为第0个元素,从0开始
    >>> num
    ['a', 0, 1, 2, 3]    //插入在第0个元素前面

posted on 2016-05-17 16:06  zhuzhu2016  阅读(153)  评论(0编辑  收藏  举报

导航