美文网首页
笔记2.列表数据类型——方法

笔记2.列表数据类型——方法

作者: Callme_Agnes | 来源:发表于2018-07-11 13:41 被阅读0次

    方法和函数是一回事,只是它是调用在一个值上。例如,如果一个列表值存储
    在spam 中,你可以在这个列表上调用index()列表方法。

    1.用index()方法在列表中查找值
    列表值有一个index()方法,可以传入一个值,如果该值存在于列表中,就返回它
    的下标。如果该值不在列表中,Python 就报ValueError。如果列表中存在重复的值,就返回它第一次出现的下标

    >>> spam = ['hello', 'hi', 'howdy', 'heyas']
    >>> spam.index('hello')
    0
    >>> spam.index('howdy howdy howdy')
    Traceback (most recent call last):
    File "<pyshell#31>", line 1, in <module>
    spam.index('howdy howdy howdy')
    ValueError: 'howdy howdy howdy' is not in list
    >>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
    >>> spam.index('Pooka')
    1
    

    2.用append()和insert()方法在列表中添加值
    要在列表中添加新值,就使用append()和insert()方法。在交互式环境中输入以
    下代码,对变量spam 中的列表调用append()方法:

    >>> spam = ['cat', 'dog', 'bat']
    >>> spam.append('moose')
    >>> spam
    ['cat', 'dog', 'bat', 'moose']
    

    前面的 append()方法调用,将参数添加到列表末尾。insert()方法可以在列表任
    意下标处插入一个值。insert()方法的第一个参数是新值的下标,第二个参数是要插
    入的新值。在交互式环境中输入以下代码:

    >>> spam = ['cat', 'dog', 'bat']
    >>> spam.insert(1, 'chicken')
    >>> spam
    ['cat', 'chicken', 'dog', 'bat']
    

    3.给remove()方法传入一个值,它将从被调用的列表中删除。

    >>> spam = ['cat', 'bat', 'rat', 'elephant']
    >>> spam.remove('bat')
    >>> spam
    ['cat', 'rat', 'elephant']
    

    4.用sort()方法将列表中的值排序
    数值的列表或字符串的列表,能用sort()方法排序。
    注意点1:不能对既有数字又有字符串值的列表排序,因为Python 不知道如何比较
    它们。
    注意点2:sort()方法对字符串排序时,使用“ASCII 字符顺序”,而不是实际的字
    典顺序
    例如,在交互式环境中输
    入以下代码:

    >>> spam = [2, 5, 3.14, 1, -7]
    >>> spam.sort()
    >>> spam
    [-7, 1, 2, 3.14, 5]
    >>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
    >>> spam.sort()
    >>> spam
    ['ants', 'badgers', 'cats', 'dogs', 'elephants']
    >>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
    >>> spam.sort()
    >>> spam
    ['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
    

    如果需要按照普通的字典顺序来排序,就在sort()方法调用时,将关键字参数
    key 设置为str.lower。

    >>> spam = ['a', 'z', 'A', 'Z']
    >>> spam.sort(key=str.lower)
    >>> spam
    ['a', 'A', 'z', 'Z']
    

    相关文章

      网友评论

          本文标题:笔记2.列表数据类型——方法

          本文链接:https://www.haomeiwen.com/subject/qzocpftx.html