zoukankan      html  css  js  c++  java
  • 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个元素前面

  • 相关阅读:
    git的最常用命令总结
    java 多线程 sleep 和wait
    java 多线程 线程的状态和操作系统中进程状态的对应关系
    IDEA的最常见快捷键
    设计模式 单例模式的几种实现方式
    spring boot 项目部署到服务器上出现的问题
    算法与数据结构 (八) HashMap源码
    算法与数据结构 (七) 查找 数组的优化方向: 二分查找和哈希查找,
    算法与数据结构 (六) 排序 三 非比较类的排序 基数排序
    Native Crash定位方法
  • 原文地址:https://www.cnblogs.com/zhuzhu2016/p/5502042.html
Copyright © 2011-2022 走看看