zoukankan      html  css  js  c++  java
  • Pyhton:List build-in function

    列表是Python中的可迭代对象之一,在讲列表的内建函数之前我们可以自己在IDE上看看都有那些内建函数,我们可以在pycharm中使用代码及其运行结果如下:

    print(dir(list))
    
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

    前面的带有__的函数我们先不管,可以看一下后面的append等函数,我们一一举例子来看

    1.append的中文意思是追加

    aList = ['1','2','3']
    aList.append('4')      # append 默认添加到列表最好
    print(aList)      
    
    
    >>>['1','2','3','4']
    

    2.clear的中文意思是清除,顾名思义

    aList.clear()        # 清空列表的内容
    print(aList)
    
    >>>[]
    

    3.copy 拷贝,此处为浅拷贝

    aList = ['1','2','3']
    bList = aList.copy()
    print(bList)
    >>>['1','2','3']

    4.count 计数

    aList = [1,2,3,2]
    n = aList.count(2)     # 返回一个对象在列表中出现的次数
    print(n)
    
    >>>2
    

    5.extend 扩展

    aList = [1,2,3,2]
    bList = [4,5,6]
    aList.extend(bList)    # extend 中的参数是一个序列,将这个序列添加到列表中
    print(aList)
    
    >>>[1,2,3,2,4,5,6]
    

    6.index 索引

    aList = [1,2,3,2]
    n = aList.index(2)     # 返回索引到的第一个参数所在列表的位置值
    print(n)
    
    >>> 1
    
    u = aList.index(2,2,len(aList))   # 后面两个参数是索引范围,分别是star 和 end
    print(u)
    
    >>> 3
    

    7.insert 插入

    aList = [1,2,3,2]
    aList.insert(2,4)      # 前面的参数表示插入的位置,后面的参数表示要插入的值
    print(aList)
    
    >>> [1, 2, 4, 3, 2]
    

    8.pop 删除

    aList = [1,2,3,2]
    aList.pop(1)         # pop 不加参数默认删除最后一个
    print(aList)
    
    >>> [1, 3, 2]
    

    9.remove 删除

    aList = [1,2,3,2]
    aList.remove(1)       # 参数为vaule
    print(aList)
    
    >>>[2, 3, 2]
    
    aList.remove(aList[1])
    print(aList)
    
    >>>[2,2]
    

    10.reverse 反转

    aList = [1,2,3,2]
    aList.reverse()       # 原地翻转列表
    print(aList)
    
    >>>[2, 3, 2, 1]
    

    11.sort 排序

    aList = ['sad','successfully','hello']
    aList.sort()
    print(aList)
    
    >>>['hello', 'sad', 'successfully']
    
    aList.sort(key = len,reverse=True)      # sort 排序函数可以指定方式排列,此处为按照长度排列。如果reverse设置成Ture,责列表以反序排列
    print(aList)
    
    >>>['successfully', 'hello', 'sad']
    

      

    以上

  • 相关阅读:
    一次难忘的问题定位
    Linux dmidecode 命令
    linux 查看静态库,动态库是32位还是64位
    MTK功能机按键事件时间设置
    linux控制主板蜂鸣器响起
    Linux 下控制蜂鸣器发声的程序
    Android Studio系列-签名打包
    使用git和github进行协同开发流程
    ero-configuration Web Application Debugging with Xdebug and PhpStorm
    sudo: unable to execute ./script.sh: no such file or directory
  • 原文地址:https://www.cnblogs.com/learnC/p/5938699.html
Copyright © 2011-2022 走看看