• 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个元素前面

  • 相关阅读:
    Web安全学习计划
    机器学习资源大全
    推荐引擎的学习资料
    《Servlet与JSP核心编程》读书笔记
    Application "org.eclipse.ui.ide.workbench" could not be found in the registry.问题的解决
    Android 百度地图开发(二)
    Linux系统编程_1_文件夹读取(实现简单ls命令)
    Bootstrap 模态框、轮播 结合使用
    cocos2d-x 3.0游戏实例学习笔记 《跑酷》移植到android手机
    Unique Binary Search Trees II
  • 原文地址:https://www.cnblogs.com/zhuzhu2016/p/5502042.html
Copyright © 2020-2023  润新知